Victor
Victor

Reputation: 17077

Pandas update one dataframe with another

I have 2 dataframes:

df1:

col1 col2 col3 

A     B    C


df2:
col1 col2 col3 col4
A     B    C    D

I want to update df1 with df2 such that if I match on col1,col2,col3, then replace col3 with col4

df_want:
col1 col2 col3
A     B    D

In SQL, it would be:

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

Upvotes: 0

Views: 60

Answers (3)

Terry
Terry

Reputation: 2811

try:

df3 = df1.merge(df2, on=['col1', 'col2', 'col3'])
del df3['col3']
df3.columns = ['col1','col2','col3']

Upvotes: 3

BENY
BENY

Reputation: 323226

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

Upvotes: 3

Rajat Jain
Rajat Jain

Reputation: 2022

Try this:

for index, row in df1.iterrows():
    if row['col1']==df2.ix[index, 'col1'] and row['col2']==df2.ix[index, 'col2'] and row['col3']==df2.ix[index, 'col3']:
        row[C]=df2.ix[index, 'col4']

Upvotes: 1

Related Questions