如何在2个数据帧之间的2列中查找具有相同值但在其他列中具有不同值的行pandas [英] How to find row with same value in 2 columns between 2 dataframes but different values in other columns pandas
本文介绍了如何在2个数据帧之间的2列中查找具有相同值但在其他列中具有不同值的行pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个数据框,样本值如下:
I have 2 dataframes with sample value as below :
df1 :
col1 cold2 cold3 cold4
a bb cc d
b aa ee e
df2 :
col1 cold2 cold3 col4
a ee ff d
e gg hh k
我想找到 2 个数据帧中的所有行在 col1+col4 中具有相同值但在 col2 或 col3 中具有不同值
i want to find all row in 2 dataframes have same value in col1+col4 but different value in col2 or col3
输出应该是这样的:
df3:
col1 cold2 cold3 cold4
a bb cc d
a ee ff d
感谢您的帮助.
推荐答案
我觉得你可以用:
#get all matched rows by columns
df = df1.merge(df2, on=['col1','col4'], suffixes=('','_'))
#filter for not matched
df = df[df['col2'] != df['col3']]
#filter columns - same like df1
df1 = df[df1.columns]
#filter added new columns
df2 = df[df.columns.difference(df2.columns).union(['col1','col4'])]
#join together - rename values for align data
df = pd.concat([df1,
df2.rename(columns=dict(zip(df2.columns, df1.columns)))],
ignore_index=True)
print (df)
col1 col2 col3 col4
0 a bb cc d
1 a ee ff d
这篇关于如何在2个数据帧之间的2列中查找具有相同值但在其他列中具有不同值的行pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文