Replacing few values in a pandas dataframe column with another value

Pulkit Jha picture Pulkit Jha · Nov 21, 2014 · Viewed 275.2k times · Source

I have a pandas dataframe df as illustrated below:

BrandName Specialty
A          H
B          I
ABC        J
D          K
AB         L

I want to replace 'ABC' and 'AB' in column BrandName by A. Can someone help with this?

Answer

Alex Riley picture Alex Riley · Nov 21, 2014

The easiest way is to use the replace method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']) and what you want to replace them with (the string 'A' in this case):

>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0    A
1    B
2    A
3    D
4    A

This creates a new Series of values so you need to assign this new column to the correct column name:

df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')