I’m looking for an efficient way to update one ow in Pandas Dataframe (like in DB).
There is an id column with unique values (ids)
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'}
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?
>Solution :
You can set_index with 'id' and update the relevant row with a dictionary by passing it to a Series:
df = df.set_index('id')
df.loc[45] = pd.Series(d)
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