简体   繁体   English

pandas:合并/合并/更新两个数据帧

[英]pandas: merge/combine/update two dataframes

I have 2 dataframes 我有2个数据帧

   id  nr   lval
0   1  one     1
1   2  two     2
2   3  one     3

   id  nr  rval
4   1  one     4
5   2  one     5
6   3  one     6

I need merge or combine these two dataframes and use column 'id' as a key. 我需要合并或组合这两个数据帧并使用列'id'作为键。 By collision (column 'nr') take the column from first dataframe. 通过碰撞(列'nr')从第一个数据帧中获取列。 Result should looks like this: 结果应如下所示:

   id  nr   lval  rval
0   1  one     1     4
1   2  two     2     5
2   3  one     3     6

As the shapes of the dfs are the same you can call combine_first , the lhs df values supercede the rhs df hence you keep the nr column values: 由于dfs的形状相同,你可以调用combine_first ,lhs df值取代rhs df,因此保留nr列值:

In [3]:

df.combine_first(df1)
Out[3]:
   id  lval   nr  rval
0   1     1  one     4
1   2     2  two     5
2   3     3  one     6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM