Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: replace string with another string

Tags:

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)
like image 924
chintan s Avatar asked Sep 20 '16 20:09

chintan s


4 Answers

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' 
like image 179
jezrael Avatar answered Sep 23 '22 07:09

jezrael


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
like image 20
EdChum Avatar answered Sep 24 '22 07:09

EdChum


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
like image 3
estebanpdl Avatar answered Sep 26 '22 07:09

estebanpdl


alternatively, you can use apply function with lambda syntax

df['prod_type'] = df['prod_type'].apply(lambda x: x.replace('respon', 'responsvie'))
like image 2
Jingyu Avatar answered Sep 25 '22 07:09

Jingyu