Home > other >  Pandas - find row by column value (id) and update its values
Pandas - find row by column value (id) and update its values

Time:01-15

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:[email protected]
1  45  ...  4215444444    HOME:[email protected]
2  20  ...  4213333333    WORK:[email protected]
3  11  ...  4215553454    WORK:[email protected] 

I want to update row with id == 45 by a dict {'phone'=' 4511111111','email':'[email protected]'}

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?

CodePudding user response:

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:[email protected]
45   4511111111     [email protected]
20   4213333333   WORK:[email protected]
11   4215553454   WORK:[email protected]
  •  Tags:  
  • Related