如何在pandas DataFrame中实现“in”和“not in”?
Pandas提供了两种方法:
Series.isin
和
DataFrame.isin
,分别用于Series和DataFrames。
根据一列过滤DataFrame(也适用于Series)
最常见的情况是在特定列上应用isin
条件以过滤DataFrame中的行。
df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
countries
0 US
1 UK
2 Germany
3 China
c1 = ['UK', 'China']
c2 = {'Germany'}
c3 = pd.Series(['China', 'US'])
c4 = np.array(['US', 'UK'])
Series.isin
接受多种类型的输入。以下方式都是获取所需内容的有效方式:
df['countries'].isin(c1)
0 False
1 True
2 False
3 False
4 True
Name: countries, dtype: bool
df[df['countries'].isin(c1)]
countries
1 UK
4 China
df[~df['countries'].isin(c1)]
countries
0 US
2 Germany
3 NaN
# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]
countries
2 Germany
df[df['countries'].isin(c3)]
countries
0 US
4 China
df[df['countries'].isin(c4)]
countries
0 US
1 UK
多列过滤
有时,您需要对多个列应用“in”成员检查,并使用一些搜索词进行过滤。
df2 = pd.DataFrame({
'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})
df2
A B C
0 x w 0
1 y a 1
2 z NaN 2
3 q x 3
c1 = ['x', 'w', 'p']
要对列"A"和"B"同时应用isin
条件,请使用DataFrame.isin
:
df2[['A', 'B']].isin(c1)
A B
0 True True
1 False False
2 False False
3 False True
因此,要保留至少有一列为True
的行,我们可以沿着第一个轴使用any
:
df2[['A', 'B']].isin(c1).any(axis=1)
0 True
1 False
2 False
3 True
dtype: bool
df2[df2[['A', 'B']].isin(c1).any(axis=1)]
A B C
0 x w 0
3 q x 3
请注意,如果您想搜索每一列,只需省略列选择步骤并执行{{}}。
df2.isin(c1).any(axis=1)
同样地,
要保留所有列都是True
的行,使用与之前相同的方式使用
all
。
df2[df2[['A', 'B']].isin(c1).all(axis=1)]
A B C
0 x w 0
值得一提的方法: numpy.isin
, query
, 列表推导式(字符串数据)
除了上面描述的方法之外,你还可以使用numpy中的等效方法:numpy.isin
。
df[np.isin(df['countries'], c1)]
countries
1 UK
4 China
df[np.isin(df['countries'], c1, invert=True)]
countries
0 US
2 Germany
3 NaN
考虑它的价值在哪里?由于开销较低,NumPy函数通常比其pandas等效函数快一些。由于这是一个元素级操作,不依赖于索引对齐,在很少情况下,该方法不是pandas“isin”的适当替代品。
使用字符串时,Pandas例程通常是迭代的,因为字符串操作难以向量化。
有很多证据表明在此处列表理解会更快。现在我们改用“in”检查。
c1_set = set(c1)
df[[x in c1_set for x in df['countries']]]
countries
1 UK
4 China
df[[x not in c1_set for x in df['countries']]]
countries
0 US
2 Germany
3 NaN
这种方法更难以指定,除非你知道自己在做什么,否则不要使用它。
最后,还有一个DataFrame.query
方法,在这个答案中已经被介绍过了。numexpr FTW!
~
。 - Trenton McKinney