提问者:小点点

如何像SQL一样使用“in”和“not in”过滤熊猫数据框架


如何实现SQL的中和不在中的等价物?

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

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'])]

但这看起来像是个可怕的玩意儿。 有人能改进吗?


共3个答案

匿名用户

您可以使用pd.series.isin

对于“in”,使用:something.isin(somethere)

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

作为一个实例:

>>> 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

匿名用户

使用。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

匿名用户

Pandas提供了两种方法:Series.isindataframe.isin分别用于序列和数据帧。

最常见的情况是对特定列应用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

null

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

null

# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]

  countries
2   Germany

null

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

  countries
0        US
4     China

null

# Filter with array
df[df['countries'].isin(c4)]

  countries
0        US
1        UK

有时,您会希望对多列的某些搜索项应用“入”成员资格检查,

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等效项:numpy.isin

# `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例程在处理字符串时通常是迭代的,因为字符串操作很难向量化。 有很多证据表明在这里列表理解会更快。 我们现在使用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,本答案中已经介绍了它。 numexpr FTW!