简体   繁体   English

Pandas(Python) - 从条件更新另一个数据框的列

[英]Pandas (Python) - Update column of a dataframe from another one with conditions

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. 也许,有一种更“规范”的方式来做到这一点。

Problem 问题

I have two dataframe that I would like to merge without having extra column and without erasing existing infos. 我有两个数据框,我想合并,没有额外的列,也没有删除现有的信息。 Example : 示例:

Existing dataframe (df) 现有数据帧(df)

   A  A2  B
0  1   4  0
1  2   5  1

Dataframe to merge (df2) 要合并的数据帧(df2)

   A  A2  B
0  1   4  2
1  3   5  2

I would like to update df with df2 if columns 'A' and 'A2' corresponds. 如果列'A'和'A2'对应,我想用df2更新df 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']

You can try this: 你可以试试这个:

df.ix[df2.loc[(df['A'] == df2['A']) & (df['A2'] ==   
df2['A2']),'B'].index.values,'B'] = \
df2.loc[(df['A'] == df2['A']) & (df['A2'] == df2['A2']),'B']

暂无
暂无

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

相关问题 Pandas(Python)-使用条件和不同的列从另一个更新数据框的列 - Pandas (Python) - Update column of a dataframe from another one with conditions and different columns 根据 pandas ZA7F5F354226B92782117DZ 中的另一个 dataframe 的条件,从一个 dataframe 中删除行 - remove rows from one dataframe based on conditions from another dataframe in pandas Python 根据条件将值从一列到另一列熊猫数据框中 - Give values from one column to another column in pandas dataframe based on conditions 将一个数据帧中的列添加到另一个 python pandas - Adding column(s) from one dataframe to another python pandas 用另一个 dataframe 中的 boolean 条件替换一个 dataframe 中的值 python pandas - replace values in one dataframe with boolean conditions from another dataframe in python pandas 如何使用来自另一列Python Pandas的相应值更新具有多个条件的列 - How to update column with multiple conditions taking a corresponding value from another column Python Pandas Pandas 更新并添加第一行 dataframe 和另一个 dataframe 中的键列 - Pandas update and add rows one dataframe with key column in another dataframe 将一列从一个 pandas dataframe 复制到另一个 - Copying a column from one pandas dataframe to another 将列从一个 pandas DataFrame 映射到另一个 - Mapping column from one pandas DataFrame to another 如何根据另一个 DataFrame 中的列更新 Pandas DataFrame 中的列 - How to update a column in pandas DataFrame based on column from another DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM