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?

1
  • 1
    Use map : df['var1'].map(df2['val1']) Commented Mar 25, 2019 at 16:12

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe try something new df2.val1.get(df.var1)
@Wen-Ben Thank you. :) I will study more on get() thanks for teaching me that. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.