首页 > 解决方案 > Pandas 用另一个数据框更新一个数据框

问题描述

我有2个数据框:

df1:

col1 col2 col3 

A     B    C


df2:
col1 col2 col3 col4
A     B    C    D

我想用 df2 更新 df1,这样如果我匹配 col1、col2、col3,然后用 col4 替换 col3

df_want:
col1 col2 col3
A     B    D

在 SQL 中,它将是:

select df1.col1,df1.col2,coalesce( df2.col4,df1.col3) as col3
from df1 left join df2 on df1.col1=df2.col1 and df1.col2=df2.col2 and df1.col3=df2.col3

标签: pandas

解决方案


Using merge

df1=df1.merge(df2,how='left')
df1.col3=df1.col4.fillna(df1.col3)
df1
Out[189]: 
  col1 col2 col3 col4
0    A    B    D    D
df1.drop('col4',1,inplace=True)
df1
Out[191]: 
  col1 col2 col3
0    A    B    D

推荐阅读