user988575
user988575

Reputation: 33

Replace values of a dataframe with the value of another dataframe

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

Upvotes: 2

Views: 97

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 31011

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'])

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195573

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

Upvotes: 1

Related Questions