Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have 2 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 the data-frames is 'A'.

How to replace values of df1's column 'B' with values of df2 in column 'B'?

RESULT of df1:

A  B

1  8 

3  10 

5  12

1 Answer

0 votes
by (36.8k points)

Maybe the 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

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Browse Categories

...