猿问

如何为Pandas数据帧实现'in'和'not in'

如何为Pandas数据帧实现'in'和'not in'

我怎样才能实现SQL的的等价物IN和NOT 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'])]

但这似乎是一个可怕的kludge。任何人都可以改进吗?


杨__羊羊
浏览 2348回答 4
4回答

函数式编程

你可以用pd.Series.isin。对于“IN”:( somewhere.isin(something)读:是否something在somewhere?)或者“不在”: ~somewhere.isin(something)举个例子:>>> df  countries0        US1        UK2   Germany3     China>>> countries['UK', 'China']>>> df.countries.isin(countries)0    False1     True2    False3     TrueName: countries, dtype: bool>>> df[df.countries.isin(countries)]  countries1        UK3     China>>> df[~df.countries.isin(countries)]  countries0        US2   Germany

摇曳的蔷薇

使用.query()方法的替代解决方案:In [5]: df.query("countries in @countries")Out[5]:  countries1        UK3     ChinaIn [6]: df.query("countries not in @countries")Out[6]:  countries0        US2   Germany

慕婉清6462132

我一直在对这样的行进行泛型过滤:criterion = lambda row: row['countries'] not in countriesnot_in = df[df.apply(criterion, axis=1)]

慕哥6287543

如何实现in和not in一个pandas DataFrame?:熊猫提供了两种方法Series.isin,并DataFrame.isin分别对系列和DataFrames。这是titular python运算符到它们等效的pandas操作的映射。╒════════╤══════════════════════╤══════════════════════╕│        │ Python               │ Pandas               │╞════════╪══════════════════════╪══════════════════════╡│ in     │ item in sequence     │ sequence.isin(item)  │├────────┼──────────────────────┼──────────────────────┤│ not in │ item not in sequence │ ~sequence.isin(item) │╘════════╧══════════════════════╧══════════════════════╛要实现“not in”,必须反转结果isin。另请注意,在pandas情况下,“ sequence”可以引用Series或DataFrame,而“ item”本身可以是可迭代的(很快就会更多)。基于ONE Column过滤DataFrame(也适用于Series)最常见的情况是isin在特定列上应用条件以过滤DataFrame中的行。df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})df  countries0        US1        UK2   Germany3     Chinac1 = ['UK', 'China']             # listc2 = {'Germany'}                 # setc3 = pd.Series(['China', 'US'])  # Seriesc4 = np.array(['US', 'UK'])      # arraySeries.isin接受各种类型作为输入。以下是获得所需内容的所有有效方法:df['countries'].isin(c1)0    False1     True2    False3    False4     TrueName: countries, dtype: bool# `in` operationdf[df['countries'].isin(c1)]  countries1        UK4     China# `not in` operationdf[~df['countries'].isin(c1)]  countries0        US2   Germany3       NaN# Filter with `set` (tuples work too)df[df['countries'].isin(c2)]  countries2   Germany# Filter with another Seriesdf[df['countries'].isin(c3)]  countries0        US4     China# Filter with arraydf[df['countries'].isin(c4)]  countries0        US1        UK过滤多个列有时,您会希望对多列使用某些搜索字词进行“入”成员资格检查,df2 = pd.DataFrame({    'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})df2   A    B  C0  x    w  01  y    a  12  z  NaN  23  q    x  3c1 = ['x', 'w', 'p']要将isin条件应用于“A”和“B”列,请使用DataFrame.isin:df2[['A', 'B']].isin(c1)      A      B0   True   True1  False  False2  False  False3  False   True从这里,为了保留至少有一列的行True,我们可以any沿第一轴使用:df2[['A', 'B']].isin(c1).any(axis=1)0     True1    False2    False3     Truedtype: booldf2[df2[['A', 'B']].isin(c1).any(axis=1)]   A  B  C0  x  w  03  q  x  3请注意,如果要搜索每个列,则只需省略列选择步骤即可df2.isin(c1).any(axis=1)同样,要保留ALL列所在的行True,请使用all与以前相同的方式。df2[df2[['A', 'B']].isin(c1).all(axis=1)]   A  B  C0  x  w  0
随时随地看视频慕课网APP

相关分类

Python
MySQL
我要回答