2

I have two pandas dataframes

df1 = pd.DataFrame({'A': [1, 3, 5], 'B': [3, 4, 5]})
df2 = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [8, 9, 10, 11, 12], 'C': ['K', 'D', 'E', 'F', 'G']})

The index of both data-frames are 'A'.
How to replace the values of df1's column 'B' with the values of df2 column 'B'?

RESULT of df1:

A  B
1  8 
3  10 
5  12
2
  • Sorry, but what's the logic behind your replace ? Commented Oct 24, 2020 at 18:45
  • Could there be duplicate values in any of column As? Commented Oct 24, 2020 at 19:14

2 Answers 2

1

Maybe dataframe.isin() is what you're searching:

df1['B'] = df2[df2['A'].isin(df1['A'])]['B'].values
print(df1)

Prints:

   A   B
0  1   8
1  3  10
2  5  12
Sign up to request clarification or add additional context in comments.

Comments

1

One of possible solutions:

wrk = df1.set_index('A').B
wrk.update(df2.set_index('A').B)
df1 = wrk.reset_index()

The result is:

   A   B
0  1   8
1  3  10
2  5  12

Another solution, based on merge:

df1 = df1.merge(df2[['A', 'B']], how='left', on='A', suffixes=['_x', ''])\
    .drop(columns=['B_x'])

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.