简体   繁体   English

Pandas - 逐列查找值(id)并更新其值

[英]Pandas - find row by column value (id) and update its values

I'm looking for an efficient way to update one ow in Pandas Dataframe (like in DB).我正在寻找一种有效的方法来更新 Pandas Dataframe 中的一个 ow(如在 DB 中)。

There is an id column with unique values (ids)有一个具有唯一值 (ids) 的id

contacts = 

   id  ... phone          email
0  33  ... +4219999999    WORK:pete@zzz.de
1  45  ... +4215444444    HOME:rot@zzz.de
2  20  ... +4213333333    WORK:aon@zzz.de
3  11  ... +4215553454    WORK:lev@zzz.de 

I want to update row with id == 45 by a dict {'phone'='+4511111111','email':'freddy@gg.com'}我想通过 dict {'phone'='+4511111111','email':'freddy@gg.com'}更新id == 45 的行

Basically, I want to replace it with data from a given dictionary.基本上,我想用给定字典中的数据替换它。

This way I can get the row:这样我可以得到该行:

contact = contacts.query(f'internal_id == "45"')

How to modify the dataframe so all the values of the row change?如何修改 dataframe 使行的所有值都发生变化?

You can set_index with 'id' and update the relevant row with a dictionary by passing it to a Series:您可以使用'id' set_index并通过将相关行传递给系列来使用字典更新相关行:

df = df.set_index('id')
df.loc[45] = pd.Series(d)

Output: Output:

          phone             email
id                               
33   4219999999  WORK:pete@zzz.de
45  +4511111111     freddy@gg.com
20   4213333333   WORK:aon@zzz.de
11   4215553454   WORK:lev@zzz.de

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM