0

I am trying to replace the values of a column in a df based on the corresponding index value pair in another df.

For example:

main df:

d = {'var1': [A, B, A, B]}
df = pd.DataFrame(data=d)
df
    var1   
0     A     
1     B     
2     A     
3     B     

Data frame with new values:

df2  val1

A     1     
B     2     

Result:

df
    var1   
0     1    
1     2    
2     1   
3     2     

I was thinking I could set var1 as a temporary index then join with df2 and then replace the var1 column with val1. Not sure if there is a better way to do this?

Mustard Tiger
  • 3,520
  • 8
  • 43
  • 68

1 Answers1

3

Use df.set_index() and series.map():

df.var1=df.var1.map(df_new.set_index('df2')['val1'])
print(df)

   var1
0     1
1     2
2     1
3     2
anky
  • 74,114
  • 11
  • 41
  • 70