Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

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'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading