![](/img/trans.png)
[英]Pandas - get dataframe rows based on matching columns with other dataframe
[英]get the matching rows for multiple columns pandas dataframe
考虑我的第一个数据帧df1
col1 col2 col3
0 hello q 1
1 world q 2
2 welcome r 3
3 hello t 4
和第二个数据帧df2
col1 col2 col3
0 hello q 2
需要输出像
col1 col2 col3
0 hello q 2
1 world q 2
2 welcome r 3
3 hello t 4
'col1'
和'col2'
应该相等,如果'col3'
不同,则获取输出并首先替换数据帧中的值
我尝试使用merge
df1.merge(df2, on=['col1', 'col2'])
col1 col2 col3_x col3_y
0 hello q 1 2
但是我不知道下一步该怎么做。
merge
, append
, drop_duplicates
df1.drop('col3', 1).merge(df2).append(df1).drop_duplicates(['col1', 'col2'])
col1 col2 col3
0 hello q 2
1 world q 2
2 welcome r 3
3 hello t 4
set_index
和combine_first
cols = ['col1', 'col2']
df2.set_index(cols).combine_first(
df1.set_index(cols)
).reset_index().astype(df1.dtypes)
col1 col2 col3
0 hello q 2
1 hello t 4
2 welcome r 3
3 world q 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.