116

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?

rachwa
  • 354
  • 1
  • 11
Pulkit Jha
  • 1,599
  • 3
  • 11
  • 18

8 Answers8

177

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')
Ogaga Uzoh
  • 1,813
  • 1
  • 9
  • 11
Alex Riley
  • 152,205
  • 43
  • 245
  • 225
  • 11
    One tricky thing if your datatypes are messed up in the dataframe (ie they look like strings but are not), use: df['BrandName'] = df['BrandName'].str.replace(['ABC', 'AB'], 'A') – ski_squaw Sep 15 '17 at 17:28
  • 7
    I had to pass `inplace=True` as well, else it wasn't changing. – Gonçalo Peres Jul 22 '20 at 17:26
  • If you would like to extend this to an entire dataframe, it will be `df = df.replace(['ABC', 'AB'], 'A')` – user42 Apr 14 '22 at 12:31
49

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
)
Ogaga Uzoh
  • 1,813
  • 1
  • 9
  • 11
I159
  • 27,484
  • 29
  • 93
  • 128
  • 1
    thanks for the snippet example, but it does not work. For one, if there is no = in the to_replace portion it errors out. For another, it is not making any replacements. Is there anyway to get a working example of the replace functionality in v 0.20.1? – Alison S May 21 '17 at 17:57
  • Does `replace` not scale well? It seems to crash my machine when replacing ~5 million rows of integers. Any way around this? – guy Sep 27 '17 at 14:29
15

loc method can be used to replace multiple values:

df.loc[df['BrandName'].isin(['ABC', 'AB'])] = 'A'
Jaroslav Bezděk
  • 4,527
  • 4
  • 23
  • 38
Saurabh
  • 6,863
  • 4
  • 43
  • 42
14

You could also pass a dict to the pandas.replace method:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this'
    }
})

This has the advantage that you can replace multiple values in multiple columns at once, like so:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this',
        'foo': 'bar',
        'spam': 'eggs'
    },
    'other_column_name': {
        'other_value_to_replace': 'other_replace_value_with_this'
    },
    ...
})
Preston
  • 6,062
  • 6
  • 45
  • 71
7

This solution will change the existing dataframe itself:

mydf = pd.DataFrame({"BrandName":["A", "B", "ABC", "D", "AB"], "Speciality":["H", "I", "J", "K", "L"]})
mydf["BrandName"].replace(["ABC", "AB"], "A", inplace=True)
Namrata Tolani
  • 801
  • 9
  • 10
4

Created the Data frame:

import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})

Now use DataFrame.replace() function:

dk.BrandName.replace(to_replace=['ABC','AB'],value='A')
Eric Aya
  • 69,000
  • 34
  • 174
  • 243
shubham ranjan
  • 369
  • 3
  • 7
4

Just wanted to show that there is no performance difference between the 2 main ways of doing it:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))

def loc():
    df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


def replace():
    df2['A'].replace(
        to_replace=2,
        value=5,
        inplace=True
    )
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Claudiu Creanga
  • 7,394
  • 10
  • 62
  • 103
3

You can use loc for replacing based on condition and specifying the column name

df = pd.DataFrame([['A','H'],['B','I'],['ABC','ABC'],['D','K'],['AB','L']],columns=['BrandName','Col2'])
df.loc[df['BrandName'].isin(['ABC', 'AB']),'BrandName'] = 'A'

Output
enter image description here