我有2个具有相同列的数据帧。列'key‘将有唯一的值。
数据帧1:-
A B key C
0 1 k1 2
1 2 k2 3
2 3 k3 5数据帧2:-
A B key C
4 5 k1 2
1 2 k2 4
2 3 k4 6如果Dataframe -2中的键与Dataframe-1匹配,我想用Dataframe -2中的值更新Dataframe -1中的行(仅针对列A和B,保持C不变)。另外,如果key是新的,则将整个行从Dataframe-2添加到Dataframe-1。
最终输出Dataframe如下所示,具有相同的列。
A B key C
4 5 k1 2 --> update
1 2 k2 3 --> no changes
2 3 k3 5 --> no changes
2 3 k4 6 --> new row发布于 2018-08-07 16:24:48
您可以对齐索引,然后对齐combine_first。由于此方法不允许指定列,因此可以在单独的步骤中从df1恢复'C'值。
# align indices
df1 = df1.set_index('key')
df2 = df2.set_index('key')
# combine dataframes preference to df2
res = df2.combine_first(df1).astype(int)
# recover C values from df1
res['C'].update(df1['C'])
# elevate index to series
res = res.reset_index()
print(res)
key A B C
0 k1 4 5 2
1 k2 1 2 3
2 k3 2 3 5
3 k4 2 3 6https://stackoverflow.com/questions/51721851
复制相似问题