Pandas系列5-DataFrame之过滤

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函数: 用于针对Series、DataFrame判断是否为null
  • notnull函数: 用于判断非null值
  • np.isnan函数: 用于针对某个标量值进行判断是否为nan(null)。需要注意的是这个函数不能用于字符串类型的值进行判断,因此如果array中有字符串类型,需要用其它方式进行判断,如isinstance
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-数据矢量化

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,050评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,538评论 1 306
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,673评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,622评论 0 218
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,047评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,974评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,129评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,893评论 0 209
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,654评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,828评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,297评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,619评论 3 262
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,326评论 3 243
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,176评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,975评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,118评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,909评论 2 278

推荐阅读更多精彩内容