pandas 根据另一个数据帧更新一个数据帧中特定列中的特定行

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

我有两个数据框,Big 和 Small,我想根据 Small 中的数据更新 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

而且这个很小:

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

我想根据 Small 的 ID 号信息更新 Big 中的行。我还想 仅更改特定的列、年龄和城市, 而不是姓名 /country/city...

所以结果 table 应该是这样的:

>>>  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*

我知道我们 eupdate 但在这种情况下我不想更改每行中的所有列,但只想更改特定的列。有办法吗?

使用DataFrame.updateID转换为index并选择列进行处理——这里只有agecity:

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