[英]How to compare two dataframes in Python pandas and output the difference?
我有兩個具有相同列數但行數不同的 df。
df1
col1 col2
0 a 1,2,3,4
1 b 1,2,3
2 c 1
df2
col1 col2
0 b 1,3
1 c 1,2
2 d 1,2,3
3 e 1,2
df1 是現有列表,df2 是更新后的列表。 預期結果是 df2 中以前不在 df1 中的任何結果。
預期結果:
col1 col2
0 c 2
1 d 1,2,3
2 e 1,2
我試過
mask = df1['col2'] != df2['col2']
但它不適用於 df 的不同行。
使用DataFrame.explode
by 列col2
中的拆分值,然后使用DataFrame.merge
和right join
和 indicato 參數,通過boolean indexing
具有right_only
和 last aggregate join
的行:
df11 = df1.assign(col2 = df1['col2'].str.split(',')).explode('col2')
df22 = df2.assign(col2 = df2['col2'].str.split(',')).explode('col2')
df = df11.merge(df22, indicator=True, how='right', on=['col1','col2'])
df = (df[df['_merge'].eq('right_only')]
.groupby('col1')['col2']
.agg(','.join)
.reset_index(name='col2'))
print (df)
col1 col2
0 c 2
1 d 1,2,3
2 e 1,2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.