chintan s chintan s - 2 months ago 15
Python Question

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)

Answer

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'