Reut
Reut

Reputation: 1592

pandas update specific rows in specific columns in one dataframe based on another dataframe

I have two dataframes, Big and Small, and I want to update Big based on the data in Small, only in specific columns.

this is Big:

>>>  ID    name    country   city         hobby     age
0   12      Meli     Peru      Lima         eating    212
1   15     Saya     USA       new-york     drinking  34
2   34     Aitel    Jordan    Amman        riding    51
3   23     Tanya    Russia    Moscow       sports    75
4   44      Gil      Spain     Madrid       paella    743

and this is small:

>>>ID       name    country   city         hobby     age
0   12      Melinda   Peru      Lima         eating    24
4   44      Gil      Spain     Barcelona     friends    21

I would like to update the rows in Big based on info from Small, on the ID number. I would also like to change only specific columns, the age and the city, and not the name /country/city....

so the result table should look like this:

>>>  ID    name    country   city         hobby     age
0   12      Meli     Peru      Lima        eating    *24*
1   15     Saya     USA       new-york     drinking  34
2   34     Aitel    Jordan    Amman        riding    51
3   23     Tanya    Russia    Moscow       sports    75
4   44      Gil      Spain    *Barcelona*   paella   *21*

I know to us eupdate but in this case I don't want to change all the the columns in each row, but only specific ones. Is there way to do that?

Upvotes: 1

Views: 1867

Answers (1)

jezrael
jezrael

Reputation: 863801

Use DataFrame.update by ID converted to index and selecting columns for processing - here only age and city:

df11 = df1.set_index('ID')
df22 = df2.set_index('ID')[['age','city']]
df11.update(df22)
df = df11.reset_index()
print (df)
   ID   name country       city     hobby   age
0  12   Meli    Peru       Lima    eating  24.0
1  15   Saya     USA   new-york  drinking  34.0
2  34  Aitel  Jordan      Amman    riding  51.0
3  23  Tanya  Russia     Moscow    sports  75.0
4  44    Gil   Spain  Barcelona    paella  21.0

Upvotes: 3

Related Questions