如何使用'in'和'not in'在Pandas dataframe中进行过滤,就像在SQL中一样

2024-05-08 22:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何实现SQL的INNOT IN等价物?

我有一个包含所需值的列表。 下面是场景:

df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']

# pseudo-code:
df[df['countries'] not in countries]

我目前的做法如下:

df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = pd.DataFrame({'countries':['UK','China'], 'matched':True})

# IN
df.merge(countries,how='inner',on='countries')

# NOT IN
not_in = df.merge(countries,how='left',on='countries')
not_in = not_in[pd.isnull(not_in['matched'])]

但这似乎是一个可怕的混乱。有人能改进吗?


Tags: indataframedfnotmergecountrieshowpd
3条回答

使用.query()方法的替代解决方案:

In [5]: df.query("countries in @countries")
Out[5]:
  countries
1        UK
3     China

In [6]: df.query("countries not in @countries")
Out[6]:
  countries
0        US
2   Germany

您可以使用^{}

用于“IN”用法:something.isin(somewhere)

或“不在”:~something.isin(somewhere)

例如:

>>> df
  countries
0        US
1        UK
2   Germany
3     China
>>> countries
['UK', 'China']
>>> df.countries.isin(countries)
0    False
1     True
2    False
3     True
Name: countries, dtype: bool
>>> df[df.countries.isin(countries)]
  countries
1        UK
3     China
>>> df[~df.countries.isin(countries)]
  countries
0        US
2   Germany

How to implement 'in' and 'not in' for a pandas DataFrame?

Pandas提供了两种方法:分别用于序列和数据帧的^{}^{}


基于一列筛选数据帧(也适用于序列)

最常见的情况是对特定列应用isin条件来筛选数据帧中的行。

df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
  countries
0        US
1        UK
2   Germany
3     China

c1 = ['UK', 'China']             # list
c2 = {'Germany'}                 # set
c3 = pd.Series(['China', 'US'])  # Series
c4 = np.array(['US', 'UK'])      # array

Series.isin接受各种类型作为输入。以下是获得你想要的一切的有效方法:

df['countries'].isin(c1)

0    False
1     True
2    False
3    False
4     True
Name: countries, dtype: bool

# `in` operation
df[df['countries'].isin(c1)]

  countries
1        UK
4     China

# `not in` operation
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

# Filter with another Series
df[df['countries'].isin(c3)]

  countries
0        US
4     China

# Filter with array
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']

要将isin条件应用于“A”和“B”列,请使用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.isinquery,列表理解(字符串数据)

除了上面描述的方法之外,您还可以使用numpy等价物:^{}

# `in` operation
df[np.isin(df['countries'], c1)]

  countries
1        UK
4     China

# `not in` operation
df[np.isin(df['countries'], c1, invert=True)]

  countries
0        US
2   Germany
3       NaN

为什么值得考虑?由于开销较低,NumPy函数通常比pandas等价函数快一点。由于这是一个不依赖于索引对齐的元素操作,因此很少有情况下此方法不适合替换pandas'isin

Pandas例程在处理字符串时通常是迭代的,因为字符串操作很难矢量化。There is a lot of evidence to suggest that list comprehensions will be faster here.。 我们现在要进行一次in检查。

c1_set = set(c1) # Using `in` with `sets` is a constant time operation... 
                 # This doesn't matter for pandas because the implementation differs.
# `in` operation
df[[x in c1_set for x in df['countries']]]

  countries
1        UK
4     China

# `not in` operation
df[[x not in c1_set for x in df['countries']]]

  countries
0        US
2   Germany
3       NaN

然而,指定它要困难得多,所以除非你知道自己在做什么,否则不要使用它。

最后,还有DataFrame.query,它已经包含在this answer中。新墨西哥自由贸易区!

相关问题 更多 >