2

I have 2 pandas dataframes:

df1

     Home  Place
a    MS    Z2
c    KM    Z3
d    RR    R2

df2

     Place1
a    A2      
c    A66
z    F32
x    K41
t    E90

I want to replace values of df2['Place1'] with df1['Place'] when indexes are matching and leave it the same when indexes are not matching.

Desired result:

     Place1
a    Z2 
c    Z3
z    F32
x    K41
t    E90

I tried to use pd.replace but it returns NAs

2 Answers 2

1

Try with update

df2['Place1'].update(df1['Place'])
df2
Out[75]: 
  Place1
a     Z2
c     Z3
z    F32
x    K41
t    E90
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your reply. But I got this error: "Cannot set a Categorical with another, without identical categories"
0

You can do this with update.

df2['Place1'] = df2['Place1'].update(df1['Place'])

2 Comments

thank you for your reply. But I got this error: "Cannot set a Categorical with another, without identical categories"
I didn't know that you have categorical columns, then you would have to set the same categories for both first. When you turn it into a Categorical, you can specify the categories.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.