大数据生活不易 我用python程序员

Pandas系列5-DataFrame之过滤与分组

2018-07-06  本文已影响16人  geekpy

Pandas的条件过滤是使用非常频繁的技巧,在这一节我们将看到各种不同的过滤技巧,如果读者有其它过滤技巧,也欢迎告诉我。

条件过滤与赋值

通过loc进行行过滤,并对过滤后的行进行赋值

In [34]: df
Out[34]:
   age  color  height
0   20   blue     165
1   30    red     175
2   15  green     185

# 注意这里赋值需要使用如下方式,而不能使用chained index
# 具体参考http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
In [38]: df.loc[df.color == 'blue','height'] = 199

In [39]: df
Out[39]:
   age  color  height
0   20   blue     199
1   30    red     175
2   15  green     185

# 表示列数据除了上例中使用'.',还可以使用'[]',如下:
In [40]: df.loc[df2['color']=='blue', 'height'] = 175

In [41]: df
Out[41]:
   age  color  height
0   20   blue     175
1   30    red     175
2   15  green     185

除了上述的过滤方式外,还可以通过query method来进行过滤查询,如下:

In [248]: df2
Out[248]:
   age  color  height
0   20  black     155
1   33  green     177
2   22    NaN     188
3   20   blue     175

In [250]: df2.query('age>20 & age<40')
Out[250]:
   age  color  height
1   33  green     177
2   22    NaN     188

空值判断

在数据处理的过程中,空值判断是非常常用的技巧,在Pandas中我们主要通过以下几种方式来判断空值。

isnull函数
In [605]: dfx
Out[605]:
    1  2
0
a1  2  4
a2  5  5
b1  5  7

In [606]: dfx.iloc[1, 1] = np.nan

In [607]: dfx
Out[607]:
    1    2
0
a1  2  4.0
a2  5  NaN
b1  5  7.0

In [608]: dfx.isnull()
Out[608]:
        1      2
0
a1  False  False
a2  False   True
b1  False  False

# 如果该列所有的值均不为null则返回False,只要有一个值为null则返回True
In [609]: dfx.isnull().any()
Out[609]:
1    False
2     True
dtype: bool

# 针对DataFrame中的所有值进行检查,只要有一个null值,则返回True
In [610]: dfx.isnull().any().any()
Out[610]: True

# 返回null值的数量
In [611]: dfx.isnull().sum().sum()
Out[611]: 1

将isnull用于过滤条件:

In [244]: df2
Out[244]:
   age  color  height
0   20  black     155
1   33  green     177
2   22    NaN     188
3   20   blue     165

In [245]: df2.loc[df2['color'].isnull(), :]
Out[245]:
   age color  height
2   22   NaN     188
notnull函数

notnull的使用与isnull类似,如下:

In [248]: df2
Out[248]:
   age  color  height
0   20  black     155
1   33  green     177
2   22    NaN     188
3   20   blue     175

In [249]: df2.loc[df2.color.notnull(), :]
Out[249]:
   age  color  height
0   20  black     155
1   33  green     177
3   20   blue     175
np.isnan函数

需要注意的是判断dataframe中某个值是否为空,不能直接用== np.nan来判断,而需要使用np.isnan函数如下

In [616]: dfx.iloc[1, 1] == np.nan
Out[616]: False

In [614]: np.isnan(dfx.iloc[1, 1])
Out[614]: True

# 其它判断方式同样不行
In [617]: dfx.iloc[1, 1] is None
Out[617]: False

In [618]: if not dfx.iloc[1, 1]: print("True")

In [619]:

isin函数

使用isin函数

In [764]: df
Out[764]:
           age  color    food  height  score state
Jane        30   blue   Steak     178    4.6    NY
Nick         2  green    Lamb     181    8.3    TX
Aaron       12    red   Mango     178    9.0    FL
Penelope     4  white   Apple     178    3.3    AL
Dean        32   gray  Cheese     175    1.8    AK
Christina   33  black   Melon     178    9.5    TX
Cornelia    69    red   Beans     178    2.2    TX

In [765]: df3 = df[df['state'].isin(['NY', 'TX'])]

In [766]: df3
Out[766]:
           age  color   food  height  score state
Jane        30   blue  Steak     178    4.6    NY
Nick         2  green   Lamb     181    8.3    TX
Christina   33  black  Melon     178    9.5    TX
Cornelia    69    red  Beans     178    2.2    TX

# 也可以使用'~'或者'-'来选择不在列表中的项
In [773]: df3 = df[-df['state'].isin(['NY', 'TX'])]

In [774]: df3
Out[774]:
          age  color    food  height  score state
Aaron      12    red   Mango     178    9.0    FL
Penelope    4  white   Apple     178    3.3    AL
Dean       32   gray  Cheese     175    1.8    AK

多过滤条件

当有多个过滤条件时,我们就需要使用逻辑操作符&, |,如下:

In [251]: df2
Out[251]:
   age  color  height
0   20  black     155
1   33  green     177
2   22    NaN     188
3   20   blue     175


In [254]: df2.loc[(df2.age>20) & (df2.color.notnull())]
Out[254]:
   age  color  height
1   33  green     177

# 注意在逻辑操作符两边的过滤条件必须使用小括号括起来,否则条件过滤不起作用,如下:
In [253]: df2.loc[df2.age>20 & df2.color.notnull()]
Out[253]:
   age  color  height
0   20  black     155
1   33  green     177
2   22    NaN     188
3   20   blue     175

过滤后的赋值计算

在实际项目中,很多时候我们根据条件选取了一些行之后,我们要针对这些行中的数据需要做些操作(比如针对age进行加1操作),更复杂的我们需要获取本行的其它列的数据共同计算和判断。这里我们可以使用如下技巧:

In [256]: df
Out[256]:
           age  color    food  height  score state
Jane        30   blue   Steak     165    4.6    NY
Nick         2  green    Lamb      70    8.3    TX
Aaron       12    red   Mango     120    9.0    FL
Penelope     4  white   Apple      80    3.3    AL
Dean        32   gray  Cheese     180    1.8    AK
Christina   33  black   Melon     172    9.5    TX
Cornelia    69    red   Beans     150    2.2    TX

# 使用mask作为我们的筛选条件
In [258]: mask = (df.color=='blue')

# 选出符合条件的行,并对age列的数据进行加1操作
In [260]: df.loc[mask, 'age'] = df.loc[mask, 'age'] + 1

In [261]: df
Out[261]:
           age  color    food  height  score state
Jane        31   blue   Steak     165    4.6    NY
Nick         2  green    Lamb      70    8.3    TX
Aaron       12    red   Mango     120    9.0    FL
Penelope     4  white   Apple      80    3.3    AL
Dean        32   gray  Cheese     180    1.8    AK
Christina   33  black   Melon     172    9.5    TX
Cornelia    69    red   Beans     150    2.2    TX


# 更复杂的,我们如果需要同一行的其它数据进行计算,那么我们就需要使用apply函数和并选出响应的列,如下:
In [262]: df_with_age_height = df.loc[mask, ['age', 'height']]

In [265]: df.loc[mask, 'score'] = df_with_age_height.apply(lambda row: row['age'] + row['
     ...: height']/100, axis=1)

In [266]: df
Out[266]:
           age  color    food  height  score state
Jane        31   blue   Steak     165  32.65    NY
Nick         2  green    Lamb      70   8.30    TX
Aaron       12    red   Mango     120   9.00    FL
Penelope     4  white   Apple      80   3.30    AL
Dean        32   gray  Cheese     180   1.80    AK
Christina   33  black   Melon     172   9.50    TX
Cornelia    69    red   Beans     150   2.20    TX

# 使用apply仍然是使用迭代的方式,我们可以通过vectorization的方式直接计算,如下
In [10]: mask = (df.color == 'red')
In [13]: df_with_age_height = df.loc[mask, ['age', 'height']]
In [14]: df.loc[mask, 'score'] = (df_with_age_height['age'] + df_with_age_height['height'])/100

In [15]: df
Out[15]:
           age  color    food  height  score state
Jane        30   blue   Steak     165   1.95    NY
Nick         2  green    Lamb      70   8.30    TX
Aaron       12    red   Mango     120   1.32    FL
Penelope     4  white   Apple      80   3.30    AL
Dean        32   gray  Cheese     180   1.80    AK
Christina   33  black   Melon     172   9.50    TX
Cornelia    69    red   Beans     150   2.19    TX

关于vectorization矢量化的相关议题,可以参考文章Pandas系列4-数据矢量化

上一篇下一篇

猜你喜欢

热点阅读