chintan s
chintan s

Reputation: 6488

pandas: replace string with another string

I have the following data frame

    prod_type
0   responsive
1   responsive
2   respon
3   r
4   respon
5   r
6   responsive

I would like to replace respon and r with responsive, so the final data frame is

    prod_type
0   responsive
1   responsive
2   responsive
3   responsive
4   responsive
5   responsive
6   responsive

I tried the following but it did not work:

df['prod_type'] = df['prod_type'].replace({'respon' : 'responsvie'}, regex=True)
df['prod_type'] = df['prod_type'].replace({'r' : 'responsive'}, regex=True)

Upvotes: 30

Views: 101997

Answers (5)

JohannesE
JohannesE

Reputation: 31

Following up to jezrael's answer, you can set inplace=True to change the data frame:

df = pd.DataFrame(
    {'prod_type':['responsive','responsive','respon','r','respon','r','responsive']},
    columns=['prod_type'])

df.replace({'prod_type': {'respon': 'responsive', 'r': 'responsive'}}, inplace=True)
df
    prod_type
0  responsive
1  responsive
2  responsive
3  responsive
4  responsive
5  responsive
6  responsive

Upvotes: 2

Jingyu
Jingyu

Reputation: 21

alternatively, you can use apply function with lambda syntax

df['prod_type'] = df['prod_type'].apply(lambda x: x.replace('respon', 'responsvie'))

Upvotes: 2

jezrael
jezrael

Reputation: 862406

Solution with replace by dictionary:

df['prod_type'] = df['prod_type'].replace({'respon':'responsive', 'r':'responsive'})
print (df)
    prod_type
0  responsive
1  responsive
2  responsive
3  responsive
4  responsive
5  responsive
6  responsive

If need set all values in column to some string:

df['prod_type'] = 'responsive' 

Upvotes: 40

estebanpdl
estebanpdl

Reputation: 1233

Other solution in case all items from df['prod_type'] will be the same:

df['prod_type'] = ['responsive' for item in df['prod_type']]
In[0]: df
Out[0]:
prod_type
0  responsive
1  responsive
2  responsive
3  responsive
4  responsive
5  responsive
6  responsive

Upvotes: 3

EdChum
EdChum

Reputation: 393873

You don't need to pass regex=True here, as this will look for partial matches, as you''re after exact matches just pass the params as separate args:

In [7]:
df['prod_type'] = df['prod_type'].replace('respon' ,'responsvie')
df['prod_type'] = df['prod_type'].replace('r', 'responsive')
df

Out[7]:
    prod_type
0  responsive
1  responsive
2  responsvie
3  responsive
4  responsvie
5  responsive
6  responsive

Upvotes: 5

Related Questions