Df1
A B C
1 1 'a'
2 3 'b'
3 4 'c'
Df2
A B C
1 1 'k'
5 4 'e'
预期输出(在Df1和Df2的差异和合并之后) 即Df1-Df2然后合并
output
A B C
1 1 'a'
2 3 'b'
3 4 'c'
5 4 'e'
差异应基于两列A和B,而不是所有三列。我不关心C列在Df2和Df1中包含什么。
答案 0 :(得分:3)
试试这个:
In [44]: df1.set_index(['A','B']).combine_first(df2.set_index(['A','B'])).reset_index()
Out[44]:
A B C
0 1 1 'a'
1 2 3 'b'
2 3 4 'c'
3 5 4 'e'
答案 1 :(得分:0)
这是一个外连接,如果在df1中未知一个值,则在df2中合并C列:
dfx = df1.merge(df2, how='outer', on=['A', 'B'])
dfx['C'] = dfx.apply(
lambda r: r.C_x if not pd.isnull(r.C_x) else r.C_y, axis=1)
dfx[['A', 'B', 'C']]
=>
A B C
0 1 1 a
1 2 3 b
2 3 4 c
3 5 4 e
答案 2 :(得分:0)
使用concat和drop_duplicates:
w*v
*所需的df:*
output = pd.concat([df1, df2])
output = output.drop_duplicates(subset = ["A", "B"], keep = 'first')