Pandas replacing or updating the entire string conditionally

I have the following df:

    Name    Status   Data
0   Mike    yes      123
1   Bob     no       456
2   Ted     yes      789
3   Fred    yes

Now I have a new one df:

0 Mike no 345
1 Fred no 123

How to update the first dfto reflect the changes? Is this a replace or merge function?

Conclusion:

    Name    Status   Data
0   Mike    no       345
1   Bob     no       456
2   Ted     yes      789
3   Fred    no       123
+4
source share
1 answer

Use updateand merge
NOTE. . I limited it dfonly to the column with which I want to combine with double brackets to ensure that my result remains in the dataframe df[['Name']]. Then I do a left merge with dfnto add the columns that I want to update. 'left'ensures that I get the same index as df, and can happily updatewithout problems.

df.update(df[['Name']].merge(dfn, 'left'))
df

   Name Status   Data
0  Mike     no  345.0
1   Bob     no  456.0
2   Ted    yes  789.0
3  Fred     no  123.0

Tip

'Name' , .

df = df.set_index('Name')
dfn = dfn.set_index('Name')

pd.DataFrame.combine_first

dfn.combine_first(df)

     Status   Data
Name              
Bob      no  456.0
Fred     no  123.0
Mike     no  345.0
Ted     yes  789.0

pd.DataFrame.update

df.update(dfn)
df

     Status   Data
Name              
Bob      no  456.0
Fred     no  123.0
Mike     no  345.0
Ted     yes  789.0
+5

Source: https://habr.com/ru/post/1696115/


All Articles