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?
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.
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.
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.
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')
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: boolean, default
False
IfTrue
, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this isTrue
.
df['BrandName'].replace( to_replace=['ABC', 'AB'], value='A', inplace=True )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With