0

How to replace data from df1 using dataframe df2 based on column A

df1 = pd.DataFrame({'A': [0, 1, 2, 0, 4],'B': [5, 6, 7, 5, 9],'C': ['a', 'b', 'c', 'a', 'e'],'E': ['a1', '1b', '1c', '1a', '1e']})
df2 = pd.DataFrame({'A': [0, 1],'B': ['new', 'new1'],'C': ['t', 't1']})
1
  • 2
    What is expected output, how looks DataFrame from sample data? Commented Jan 26, 2020 at 16:21

2 Answers 2

2

Use DataFrame.merge with left join, replace missing values by original DataFrame by DataFrame.fillna and last filter columns by df1.columns:

df = df1.merge(df2, on='A', how='left', suffixes=('_','')).fillna(df1)[df1.columns]
print(df)
   A     B   C   E
0  0   new   t  a1
1  1  new1  t1  1b
2  2     7   c  1c
3  0   new   t  1a
4  4     9   e  1e
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an option.

##set index to be the same
df1 = df1.set_index('A')
df2 = df2.set_index('A')

##update df1
df1.loc[df2.index,df2.columns] = df2

##reset the index to get it back to a column
df1 = df1.reset_index()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.