假設我有一個這樣的資料框:
df1:
col1 col2
0 data1 math
1 data1 math2
2 data2 math
3 data3 math
4 data4 math2
df2:
col1 col2
0 data1 math
1 data1 math2
2 data1 math3
3 data2 math2
4 data3 math
5 data4 math2
6 data4 math3
我如何基于 col1 和 col2 比較這兩個資料幀并獲得差異(洗掉與 df1 匹配的所有行)并具有這樣的資料幀:
col1 col2
0 data1 math3
1 data2 math2
2 data4 math3
我試過這個,但它不起作用:
df3 = df2[~(df2['col2'].isin(df1['col2']))].reset_index(drop=True)
uj5u.com熱心網友回復:
您的解決方案應該使用比較MultiIndex或元組更改:
df3 = df2[~df2.set_index(['col1','col2']).index.isin(df1.set_index(['col1','col2']).index)].reset_index(drop=True)
df3 = df2[~df2[['col1','col2']].apply(tuple, 1).isin(df1[['col1','col2']].apply(tuple, 1))].reset_index(drop=True)
uj5u.com熱心網友回復:
您可以執行合并indicator=True并僅保留right_only行:
(df1.merge(df2, on=['col1', 'col2'], how='outer', indicator=True)
.query('_merge == "right_only"')
.drop(columns='_merge').reset_index(drop=True)
)
輸出:
col1 col2
0 data1 math3
1 data2 math2
2 data4 math3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387631.html
上一篇:Pandas-創建具有唯一值的組
