0

I have two df's

df1:

index    text
1        string1
2        string2
3        string3
4        a
5        string5
6        a

df2:

index    text
4        string4
6        string6

How can I replace the text 'a' in df1 with the values found in df2 based on the index, so that it shows as below.

df3:

index    text
1        string1
2        string2
3        string3
4        string4
5        string5
6        string6

2 Answers 2

1

You can use pandas update as:

df1.set_index('index',inplace=True)
df2.set_index('index',inplace=True)
df1.update(df2) #df1 is changed

Or

df1.loc[df2.index,'text'] = df2['text'] #df1 is changed

Or The output to be in df3 then

df3 = df1.copy()
df3.update(df2) #df3 is changed

All of them produces:

       text
index   
1   string1
2   string2
3   string3
4   string4
5   string5
6   string6
Sign up to request clarification or add additional context in comments.

3 Comments

Please update your answer, it should be df1.set_index('index', drop=True, inplace=True) and df2.set_index('index', drop=True, inplace=True) in order to get the desired output shown.
@Nand Checked in pandas 0.23.4 drop=True is not needed.
wonderful!, this is exactly what i needed,had to do a simple column name change for it to work in my case
0

This will work

pd.merge(df1[[]], df2, left_index=True, right_index=True)

or

df2.loc[df1.index] 

1 Comment

merge and loc added more columns than i needed, thanks, but update() did the trick for me

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.