Python | Pandas DataFrame最常用的十二个方法总结

在data science领域,pandas是python最常用的library,而DataFrame又是pandas最核心的数据结构。用久了,发现与pandas DataFrame相关的常用的方法其实就那么几个,只要能熟练掌握便能解决大部分需求了。

1. Create a pandas DataFrame

如果数据已经以list的形式存在了的话,最常用的方法是直接pass in 一个字典,比如:

import pandas as pd
name_lst = ['John','Mike']
age_lst = [12,30]
city_lst = ['New York City','Paris']
df = pd.DataFrame({'name':name_lst,'age':age_lst,'city':city_lst})

如果没有,可以创建一个空DataFrame,再以append的方式(见下文)添加行。(columns参数定义了列的名字,是optional的。)

df = pd.DataFrame(columns=['name','age','city'])

2. DataFrame.head()

The most basic, but also the most frequently used method, especially useful when you have a large DataFrame and you just want to glance over the first few rows to make sure everything looks right.

df.head(5)  # returns the first 5 rows

3. DataFrame.columns

Technically this is not a method, but an attribute of pandas DataFrame. This comes in handy when the DataFrame you are dealing with has numerous columns and you would like to find the name of a certain column.

df.columns

4. DataFrame.loc() & DataFrame.iloc()

筛选DataFrame的两个方法,使用方法非常灵活多样,这点documentation里有详细的例子介绍。二者的区别:loc()的筛选是基于labels(column names)和条件(也就是boolean arrays),而iloc()的筛选是基于index的。
比如:

df.loc[df['age']<18]   #筛选出未成年人
df.iloc[:5]            #筛选出前五行

loc()也是pandas推荐的用来set values的方法,因为它可以帮助避免chained assignment的问题。比如下面这个例子:

df[df['age'<18]]['age']='underage'   # chained assignment problem

上面的代码并不会更改原本df的值,因为df[df['age'<18]]只是原DataFrame的一个copy。因此,跑上面那段代码会得到以下提示:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
正确的做法是用loc()方法:

df.loc[df['age']<18, 'age']='underage'   # correct

5. DataFrame.iterrows()

The method to use if you want to iterate through the entire DataFrame, works similar to Python dictionary’s items.

for index, row in df.iterrows():
    # code block

6. DataFrame.append()

Append another DataFrame under the original DataFrame. Return a new DataFrame object.

df_new = df.append(pd.DataFrame({'name':['Kelly'],'age':[42],'city':['Beijing']}))

7. pd.merge()

Equivalent to SQL join,提供inner, outer, left, right几种选项。比如我们有一个消费者信息表fct_customer和一个订单信息表fct_order,其中共有的column是消费者编号customer_id,现在希望只找到所有下过订单的顾客的信息,则可以使用inner join:

old_customer = pd.merge(fct_customer, fct_order, how='inner', on='customer_id')

如果两个表里对消费者编号这一列的叫法不同也没有关系,可以不使用on这个参数,而分别pass inleft_onright_on两个参数。

8. DataFrame.groupby()

Equivalent to SQL groupby,提供若干aggregate functions选项,常用的就是mean(), sum(), count()等几种。比如,想查看df中每个城市的人平均年龄是多少:

df.groupby(how='city').mean()

9. DataFrame.fillna() & DataFrame.dropna()

非常实用的两个方法,可以作为read in一个DataFrame后的第一步来使用,毕竟如果DataFrame里含有nan的话难免会在做一些操作时报错。注意,默认该方法会return a new DataFrame,如果希望修改原DataFrame的话需要pass in inplace=True

df.fillna(0, inplace=True)

10. DataFrame.drop_duplicates()

有点类似于SQL里的distinct关键词,可以选择一个subset of columns,去除它们中带有相同值的行。

df.drop_duplicates(subset=['city','age'], inplace=True)

11. DataFrame.sort_values()

Return the sorted DataFrame. 常用的参数有:

  • by:the column name or the list of column names to be sorted
  • ascending:由小到大还是由大到小
  • axis:0为横行,1为竖列
  • inplace:修改原DataFrame还是return a new DataFrame
df_sorted = df.sort_values(by=['city','age'], ascending=False)

12. DataFrame.reset_index()

不起眼但经常会用到的方法。尤其是在用完drop_duplicates(), sort_values()等一些会删除某些行或改变行的顺序的方法后,默认会保留原index number,因此会出现sort完以后编号全部乱掉的情况。这时重置一下index就十分有用了。
需要注意的是该方法default设置为重置后将把旧的index作为一列保留在DataFrame中,如果不想要需要设置drop=True

df.reset_index(drop=True, inplace=True)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章