Qwertford
Qwertford

Reputation: 1189

How to find the row of a dataframe from column value then update row with dictionary?

I have a dataframe of the form:

import pandas as pd
df = pd.DataFrame(None,columns= ['Name','Age','Asset'])
df = df.append({'Name':'John','Age':10,'Asset':'Bike'},ignore_index=True)
df = df.append({'Name':'Sarah','Age':17,'Asset':'Laptop'},ignore_index=True)
df = df.append({'Name':'Noah','Age':14,'Asset':'Book'},ignore_index=True)
df

    Name    Age     Asset
0   John    10  Bike
1   Sarah   17  Laptop
2   Noah    14  Book

Now I want to take a dictionary {'Name' :'John','Age':11,'Asset' :'Phone'} and finds the row of the df with name John, change the age to 11 and Change the Asset to 'Phone'. Assume every column of the dataframe is a key in the dicionary.

since iloc retrieves a row, I thought this would work,

df.loc[df['Name'] == 'John'] = {'Name' :'John','Age':11,'Asset' :'Phone'}

However, this doesn't work and you need to update with a list.

What's the efficient way to update a dataframe row with a dictionary?

Upvotes: 1

Views: 85

Answers (3)

Andy L.
Andy L.

Reputation: 25239

You may assign dict.values() directly to the the slice you want modify by .loc as follows (Note: this works on Python 3.5+ because the order of d is guaranteed by the insertion order. On Python < 3.5, you need use collections.OrderedDict):

d = {'Name' :'John','Age':11,'Asset' :'Phone'}
df.loc[df.Name.eq(d['Name']), :] = list(d.values())

Out[643]:
    Name Age   Asset
0   John  11   Phone
1  Sarah  17  Laptop
2   Noah  14    Book

Upvotes: 1

anky
anky

Reputation: 75080

You can set the index to Name and then call df.update() to update the dataframe referring to the matching index. Finally .reset_index() to reset the index to columns:

d={'Name' :'John','Age':11,'Asset' :'Phone'}

d_=pd.DataFrame().from_dict(d,'index').T
m_=df.set_index('Name')
m_.update(d_)
df=m_.reset_index()

    Name Age   Asset
0   John  11   Phone
1  Sarah  17  Laptop
2   Noah  14    Book

Upvotes: 1

run-out
run-out

Reputation: 3184

I think you are trying to make the changes to more than just John? But for any dictionary?

Let's set the dictionary you provided as

di = {'Name' :'John','Age':11,'Asset' :'Phone'}

Then we can filter using .loc rows by 'Name', and select columns 'Age' and 'Asset', then set values from the dictionary.

df.loc[df['Name'] == di['Name'], ['Age', 'Asset']] = [di['Age'], di['Asset']]

print(df)

    Name Age   Asset
0   John  11   Phone
1  Sarah  17  Laptop
2   Noah  14    Book

Upvotes: 1

Related Questions