[英]Pandas update one df from another based on other columns value
I have two dataframes:我有两个数据框:
df1: df1:
A B C
0 1 3 5
1 2 4 6
df2: df2:
A B C
0 1 3 50
1 3 5 -1
2 2 4 60
And now I want to update df1 from df2 based on the same values from A
and B
, to get something like this:现在我想根据
A
和B
的相同值从 df2 更新 df1 ,以获得如下内容:
A B C
0 1 3 50
1 2 4 60
What did I try:我尝试了什么:
.update()
results in A[1] == 3
nad B[1] == 5
, it just goes in order, doesn't match the key (because I cannot specify it there) .update()
结果A[1] == 3
nad B[1] == 5
,它只是按顺序进行,与密钥不匹配(因为我不能在那里指定它).merge()
with left join and on=["A", "B"]
- best I got so far, it does preserve the result df to just 2 rows with A=1,2
and B=3,4
, but it adds columns C_x
and C_y
, the latter with the values I want, but I want them to be in C
.merge()
with left join and on=["A", "B"]
- 到目前为止我得到的最好的结果,它确实将结果 df 保留为A=1,2
和B=3,4
的 2 行,但是它添加了列C_x
和C_y
,后者具有我想要的值,但我希望它们位于C
Is there a clean way to do this, or should I go for .merge()
and just remove the column with _x
suffix + rename the C_y
to C
?有没有一种干净的方法可以做到这一点,或者我应该为
.merge()
并删除带有_x
后缀的列 + 将C_y
重命名为C
?
Drop C in df1 then merge将 C 放入 df1 然后合并
df1.drop('C', axis=1).merge(df2, on=['A', 'B'], how='left')
A B C
0 1 3 50
1 2 4 60
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.