[英]how to use pandas isin for multiple columns
在col1
和col2
上執行內部合並:
import pandas as pd
df1 = pd.DataFrame({'col1': ['pizza', 'hamburger', 'hamburger', 'pizza', 'ice cream'], 'col2': ['boy', 'boy', 'girl', 'girl', 'boy']}, index=range(1,6))
df2 = pd.DataFrame({'col1': ['pizza', 'pizza', 'chicken', 'cake', 'cake', 'chicken', 'ice cream'], 'col2': ['boy', 'girl', 'girl', 'boy', 'girl', 'boy', 'boy']}, index=range(10,17))
print(pd.merge(df2.reset_index(), df1, how='inner').set_index('index'))
產量
col1 col2
index
10 pizza boy
11 pizza girl
16 ice cream boy
reset_index
和set_index
調用的目的是保留df2
的索引,就像您發布的所需結果一樣。 如果索引不重要,那么
pd.merge(df2, df1, how='inner')
# col1 col2
# 0 pizza boy
# 1 pizza girl
# 2 ice cream boy
就足夠了。
或者,您可以從col1
和col2
列構造MultiIndex
,然后調用MultiIndex.isin
方法:
index1 = pd.MultiIndex.from_arrays([df1[col] for col in ['col1', 'col2']])
index2 = pd.MultiIndex.from_arrays([df2[col] for col in ['col1', 'col2']])
print(df2.loc[index2.isin(index1)])
產量
col1 col2
10 pizza boy
11 pizza girl
16 ice cream boy
謝謝你! 這是一個小更新。
import pandas as pd
df1 = pd.DataFrame({'col1': ['pizza', 'hamburger', 'hamburger', 'pizza', 'ice cream'], 'col2': ['boy', 'boy', 'girl', 'girl', 'boy']}, index=range(1,6))
df2 = pd.DataFrame({'col1': ['pizza', 'pizza', 'chicken', 'cake', 'cake', 'chicken', 'ice cream'], 'col2': ['boy', 'girl', 'girl', 'boy', 'girl', 'boy', 'boy']}, index=range(10,17))
df1[df1.set_index(['col1','col2']).index.isin(df2.set_index(['col1','col2']).index)]
返回:
col1 col2
1 pizza boy
4 pizza girl
5 ice cream boy
如果不知何故你必須堅持isin
或否定版本~isin
。 您可以先創建一個新列,將col1
和col2
連接起來。 然后使用isin
過濾您的數據。 這是代碼:
import pandas as pd
df1 = pd.DataFrame({'col1': ['pizza', 'hamburger', 'hamburger', 'pizza', 'ice cream'], 'col2': ['boy', 'boy', 'girl', 'girl', 'boy']}, index=range(1,6))
df2 = pd.DataFrame({'col1': ['pizza', 'pizza', 'chicken', 'cake', 'cake', 'chicken', 'ice cream'], 'col2': ['boy', 'girl', 'girl', 'boy', 'girl', 'boy', 'boy']}, index=range(10,17))
df1['indicator'] = df1['col1'].str.cat(df1['col2'])
df2['indicator'] = df2['col1'].str.cat(df2['col2'])
df2.loc[df2['indicator'].isin(df1['indicator'])].drop(columns=['indicator'])
這使
col1 col2
10 pizza boy
11 pizza girl
16 ice cream boy
如果您這樣做,請記住確保連接兩列不會產生誤報,例如df1
中的123
和456
的連接以及df2
中的12
和3456
的連接將匹配,即使它們各自的列不匹配。 您可以通過附加sep
參數來解決此問題。
df1['indicator'] = df1['col1'].str.cat(df1['col2'], sep='$$$')
df2['indicator'] = df2['col1'].str.cat(df2['col2'], sep='$$$')
一種可能的方法是定義您自己的檢查功能並在數據幀上執行apply
。
例如,如果您知道需要過濾的組合列表(可以預先從數據框中提取此列表):
filter_list_multicols = [["book", "cat"], ["table", "dog"], ["table", "cat"], ["pen", "horse"], ["book", "horse"]]
然后你可以這樣定義一個檢查函數:
def isin_multicols_check(stationary_name, animal_name):
for filter_pair in filter_list_multicols:
if (stationary_name == filter_pair[0]) and (animal_name == filter_pair[1]):
return True
return False
示例數據框:
df = pd.DataFrame([
[1, "book", "dog"], [2, "pen", "dog"], [3, "pen", "rat"], [4, "book", "horse"], [5, "book", "cat"]
],
columns=["S.N.", "stationary_name", "animal_name"])
df
S.N. stationary_name animal_name
1 book dog
2 pen dog
3 pen rat
4 book horse
5 book cat
現在,使用 pandas apply
調用該函數:
df["is_in"] = df.apply(lambda x: isin_multicols_check(x.stationary_name, x.animal_name), axis=1)
df
S.N. stationary_name animal_name is_in
1 book dog false
2 pen dog false
3 pen rat false
4 book horse true
5 book cat true
結果:
is_in = df[df["is_in"]==True]
not_is_in = df[df["is_in"]==False]
最好的方法是將 dict 傳遞給 isin()
此外,文檔https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isin.html顯示了如何傳遞字典的另一個示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.