0

I have the following problem. I have a dataframe that contains an important value for another dataframe and it is necessary to take it directly from there, here is an example:

import pandas as pd
df = pd.DataFrame({'user': ['A', 'B', 'C'], 
                   'income': [1, 5, 4]})

df_v2 = pd.DataFrame({'user': ['A', 'B', 'C'], 
                   'name': ['John', 'Peter', 'Anne']})

I must check if the user is the same between the two dataframes, if so, in the df_2 I must add the income column, the result would be the following:


df_v2 = pd.DataFrame({'user': ['A', 'B', 'C'], 
                      'name': ['John', 'Peter', 'Anne']
                      'income': [1, 5, 4]})

Any suggestions?

isaac.af95
  • 113
  • 7

2 Answers2

1

You can add a new column and look up the value from the other data frame like this:

df_v2['income'] = df_v2['user'].map(df.set_index('user')['income'])
Rutger
  • 593
  • 5
  • 11
0

df_v2 = df_v2.merge(df, how='left')

Aryerez
  • 3,417
  • 2
  • 9
  • 17
  • While this answer may answer the question it would be good if you explained the code a bit, e.g. why it is built that way, how it works etc. – Dominik May 22 '21 at 12:42