Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing few values in a pandas dataframe column with another value

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?

like image 527
Pulkit Jha Avatar asked Nov 21 '14 11:11

Pulkit Jha


People also ask

How do I change multiple values in a column in pandas?

Pandas replace multiple values in column replace. By using DataFrame. replace() method we will replace multiple values with multiple new strings or text for an individual DataFrame column. This method searches the entire Pandas DataFrame and replaces every specified value.

How can I replace all values in a DataFrame with another value?

replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.

How do I change a specific value in pandas?

Pandas DataFrame replace() MethodThe replace() method replaces the specified value with another specified value. The replace() method searches the entire DataFrame and replaces every case of the specified value.


2 Answers

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') 
like image 77
Alex Riley Avatar answered Sep 20 '22 12:09

Alex Riley


Replace

DataFrame object has powerful and flexible replace method:

DataFrame.replace(         to_replace=None,         value=None,         inplace=False,         limit=None,         regex=False,          method='pad',         axis=None) 

Note, if you need to make changes in place, use inplace boolean argument for replace method:

Inplace

inplace: boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this is True.

Snippet

df['BrandName'].replace(     to_replace=['ABC', 'AB'],     value='A',     inplace=True ) 
like image 36
I159 Avatar answered Sep 21 '22 12:09

I159