Naik
Naik

Reputation: 1255

Update a row of a dataframe based on a dictionary

I have a data frame having these columns:

df.columns = ['Jan', 'Feb', 'Mar', 'Apr', 'May', ...]

Now, I want to update each row of my df using a dictionary: let us say that I have this dictionary for the first row:

dic_ = {'May':3, 'Jul':8}

How can I update each row of df using the above dictionary? Please note that this dictionary is different for each row and it does not include all columns of df.

Upvotes: 0

Views: 88

Answers (1)

anky
anky

Reputation: 75080

You can use assign here:

df = pd.DataFrame(columns=['Jan', 'Feb', 'Mar', 'Apr', 'May'])
print(df)
df_updated = df.assign(**pd.DataFrame.from_dict(dic_,orient='index').T)
print(df_updated)

Empty DataFrame
Columns: [Jan, Feb, Mar, Apr, May]
Index: []

   Jan  Feb  Mar  Apr  May  Jul
0  NaN  NaN  NaN  NaN    3    8

Upvotes: 1

Related Questions