我有两个数据框:
>>> df1
[Output]: col1 col2 col3 col4
a abc 10 str1
b abc 20 str2
c def 20 str2
d abc 30 str2
>>> df2
[Output]: col1 col2 col3 col5 col6
d abc 30 str6 47
b abc 20 str5 66
c def 20 str7 53
a abc 10 str5 21
以下是我想要生成的内容:
>>> df_merged
[Output]: col1 col2 col5
a abc str5
b abc str5
c def str7
d abc str6
我不想生成超过 4 行,这通常是我尝试合并数据帧时发生的情况。感谢您的提示!
Use .merge
通过子选择正确的列并使用col1
& col2
作为关键列:
df1[['col1', 'col2']].merge(df2[['col1', 'col2', 'col5']], on=['col1', 'col2'])
col1 col2 col5
0 a abc str5
1 b abc str5
2 c def str7
3 d abc str6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)