我有两个数据帧,左右。右边的键(列)是左边的键的一部分。我想保持列数据不正确并放在左边,我不在乎左边的重叠键数据:
left = pd.DataFrame({'key1': ['Knan', 'Knan', 'Knan', 'Knan'],
'key2': ['Kxx1', 'Kxx2', 'Kxx3', 'Kxx4'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K5', 'K6', 'K7', 'K8']})
for key in right.keys():
if key in left.keys():
left[key] = right[key]
使用merge或concat还是有更好的方法吗?
答案 0 :(得分:0)
IIUC,您需要combine_first
:
df_out = right.combine_first(left)
print(df_out)
输出:
A B key1 key2
0 A0 B0 K0 K5
1 A1 B1 K1 K6
2 A2 B2 K1 K7
3 A3 B3 K2 K8