Pandas(Python)-使用条件从另一个数据框更新数据框的列 [英] Pandas (Python) - Update column of a dataframe from another one with conditions

查看:118
本文介绍了Pandas(Python)-使用条件从另一个数据框更新数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题,找到了解决方案,但我认为这样做是错误的方法. 也许,还有一种更规范"的方式来做到这一点.

I had a problem and I found a solution but I feel it's the wrong way to do it. Maybe, there is a more 'canonical' way to do it.

问题

我有两个要合并的数据框,没有多余的列,也没有擦除现有的信息.例子:

I have two dataframe that I would like to merge without having extra column and without erasing existing infos. Example :

现有数据框(df)

   A  A2  B
0  1   4  0
1  2   5  1

要合并的数据框(df2)

Dataframe to merge (df2)

   A  A2  B
0  1   4  2
1  3   5  2

如果列'A'和'A2'对应,我想用df2更新df. 结果将是(:

I would like to update df with df2 if columns 'A' and 'A2' corresponds. The result would be (:

   A  A2    B
0  1   4  2.0 <= Update value ONLY
1  2   5  1.0

这是我的解决方案,但我认为这不是一个很好的解决方案.

Here is my solution, but I think it's not a really good one.

import pandas as pd

df = pd.DataFrame([[1,4,0],[2,5,1]],columns=['A','A2','B'])

df2 = pd.DataFrame([[1,4,2],[3,5,2]],columns=['A','A2','B'])

df = df.merge(df2,on=['A', 'A2'],how='left')
df['B_y'].fillna(0, inplace=True)
df['B'] = df['B_x']+df['B_y']
df = df.drop(['B_x','B_y'], axis=1)
print(df)

有人能做得更好吗? 谢谢!

Does anyone has a better way to do ? Thanks !

推荐答案

是的,无需合并即可完成:

Yes, it can be done without merge:

rows = (df[['A','A2']] == df2[['A','A2']]).all(axis=1)
df.loc[rows,'B'] = df2.loc[rows,'B']

这篇关于Pandas(Python)-使用条件从另一个数据框更新数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆