简体   繁体   English

根据条件使用另一个数据帧列值更新一个数据帧值

[英]Update one dataframe value with another dataframe column value based on the condition

I have two dataframe say df1 and df2 . 我有两个数据帧说df1df2

df1:

id code remarks
1   a12  
2   b32  
3   c12

df2:

id code remarks
1   aaa12  ok
2   b32    done
3   ccc12  not ok

I want to update the df1 remarks value with df2 remarks value based on the id and code . 我想根据idcodedf2备注值更新df1备注值。

Here second value matches ( id-2 , code-b32 ) so update the value of remarks 'done' with df1 remarks column. 这里第二个值匹配( id-2 , code-b32 ),所以用df1 remarks列更新备注'done'的值。

End result of df1 will be like below, df1最终结果如下所示,

df1:

id code remarks
1   a12  
2   b32  done
3   c12

So far i tried like below, I know this is not correct, but i need something like this 到目前为止,我尝试如下,我知道这是不正确的,但我需要这样的东西

df1_key = df1['id'].astype(str) + df1['code'].astype(str)
df2_key = df2['id'].astype(str) + df2['code'].astype(str)

df['flag'] = df1_key.isin(df2_key, df1['remarks']=df2['remarks'])

According to this one i tried the below also, but did n't work for me. 根据这个,我也尝试了以下,但没有为我工作。

 df3 = df1.merge(df2[['remarks']], on=['id','code'], how='left')

Use DataFrame.merge with filtered columns by list: 按列表使用DataFrame.merge和筛选的列:

df3 = df1[['id','code']].merge(df2, on=['id','code'], how='left')

Or by DataFrame.drop : 或者通过DataFrame.drop

df3 = df1.drop('remarks', axis=1).merge(df2, on=['id','code'], how='left')

print (df3)
   id code remarks
0   1  a12     NaN
1   2  b32    done
2   3  c12     NaN

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

相关问题 根据条件将一个 dataframe 中的列值设置为另一个 dataframe 列 - Setting value of columns in one dataframe to another dataframe column based on condition 使用来自另一个具有条件的数据帧的值更新熊猫数据帧列 - update pandas dataframe column with value from another dataframe with condition 根据条件从另一个数据框设置数据框列的值 - Setting value for dataframe column from another dataframe based on condition 基于另一个 dataframe 的行值对一个 dataframe 中的列求和 - Sum column in one dataframe based on row value of another dataframe 如何根据数据框的另一列中的条件查找列中的最小值? - How to find minimum value in a column based on condition in an another column of a dataframe? 使用 lambda 如果基于 Pandas dataframe 中另一列的值的列的条件 - Using lambda if condition to column based on value of another column in Pandas dataframe Pyspark DataFrame 列基于另一个 DataFrame 值 - Pyspark DataFrame column based on another DataFrame value 根据另一列条件替换 dataframe 中的空白值 - Replace blank value in dataframe based on another column condition 根据另一列中的条件从 Pandas 数据框中提取值 - Extract Value From Pandas Dataframe Based On Condition in Another Column 如何在另一个 dataframe 中根据条件添加列值? - How to add column value based on condition in another dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM