4 回答

TA貢獻1807條經驗 獲得超9個贊
你可以用pd.Series.isin
。
對于“IN”:( somewhere.isin(something)
讀:是否something
在somewhere
?)
或者“不在”: ~somewhere.isin(something)
舉個例子:
>>> 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

TA貢獻1804條經驗 獲得超2個贊
我一直在對這樣的行進行泛型過濾:
criterion = lambda row: row['countries'] not in countries
not_in = df[df.apply(criterion, axis=1)]

TA貢獻1831條經驗 獲得超10個贊
如何實現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
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
過濾多個列
有時,您會希望對多列使用某些搜索字詞進行“入”成員資格檢查,
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)
同樣,要保留ALL列所在的行True,請使用all與以前相同的方式。
df2[df2[['A', 'B']].isin(c1).all(axis=1)]
A B C
0 x w 0
添加回答
舉報