AmanArora
AmanArora

Reputation: 2499

Change column values based on another column (don't change if not in dictionary)

I want to update my "Pack_Size" column based on "Product_ID". I have a dictionary pack_size_dict with keys as Product_ID and Values as Pack_Size:

{'1320383': '200gm', '19958': '50ml', '255354': '150ml+100ml', '2810025': '80g+10ml', '288075': '50gm', '4692429': '7gm', '4736814': '50gm + 30ml', '4906532': '565ml', '5041356': '0.3g+3g', '5146273': '25 pcs', '9371': '90g'}

I did df['Pack_Size']=df['Product_ID'].map(pack_size_dict)

but this gives NaNs if Product_ID is not in this dictionary. I want to keep already existing Pack_Size in my dataframe if Product_ID is not in dictionary and change only if it exists in this dictionary.

Upvotes: 1

Views: 137

Answers (1)

Nick
Nick

Reputation: 147166

You can use fillna to replace the NaN values with the original Pack_size:

df['Pack_Size'] = df['Product_Id'].map(pack_size_dict).fillna(df['Pack_Size'])

Upvotes: 1

Related Questions