[英]Pandas - get dataframe rows based on matching columns with other dataframe
假設有兩個數據幀,一個叫 df1,另一個叫 df2:
df1 = pd.DataFrame.from_dict({'col1': [1,9,4,7],
'col2': [6,4,3,7],
'col3': [1,4,7,8]})
df2 = pd.DataFrame.from_dict({'col1': [4,8,2,7],
'col2': [7,3,3,3],
'col3': [2,7,7,5]})
df1:
col1 col2 col3
0 1 6 1
1 9 4 4
2 4 3 7
3 7 7 8
df2:
col1 col2 col3
0 4 7 2
1 8 3 7
2 2 3 7
3 7 3 5
如您所見,在 'col2' 和 'col3' 的兩個數據幀中,我們都有 (3, 7) 的組合。 我想迭代 df1 的行,並使用 col2 和 col3 作為 df2 的過濾器,這樣對於 df1 中的索引(0、1、3),我們將收到一個空的 dataframe,但對於第 2 行,我們將收到一個 dataframe 與 df2 中的索引行 (1,2) 及其原始索引:
new dataframe:
col1 col2 col3
1 8 3 7
2 2 3 7
在這里為任何感興趣的人找到解決方案: Select 行來自 Pandas DataFrame 與另一個 ZBA834Z5C175EB8E12 中的列值完全相同
df1.merge(df2[['col2', 'col3']])
您可以將pd.merge
與 how as inner
一起使用
df2.reset_index().merge(df1[['col2','col3']], how="inner").set_index('index')
col1 col2 col3
index
1 8 3 7
2 2 3 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.