Replace all instances of a value to another specific value

Replace all instances of a value to another specific value

Problem Description:

I have this part of the df

        x            y         d   n
0   -17.7    -0.785430  0.053884  y1
1   -15.0 -3820.085000  0.085000  y4
2   -12.5     2.138833  0.143237  y3
3   -12.4     1.721205  0.251180  y3

I want to replace all instances of y3 for "3rd" and y4 for "4th" in column n

Output:

        x            y         d   n
0   -17.7    -0.785430  0.053884  y1
1   -15.0 -3820.085000  0.085000  4th
2   -12.5     2.138833  0.143237  3rd
3   -12.4     1.721205  0.251180  3rd

Solution – 1

Simple. You can use Python str functions after .str on a column.

df['n'] = df['n'].str.replace('y3', '3rd').replace('y4', '4th')

OR

You can select the specific columns and replace like this

df[df['n'] == 'y3'] = '3rd'
df[df['n'] == 'y4'] = '4th'

Choice is yours.

Solution – 2

You can use regex and define a dict for replace.

dct_rep = {'y3':'3rd' , 'y4':'4th'}


df['n'] = df['n'].str.replace(r'(y3|y4)', 
                              lambda x: dct_rep.get(x.group(), 'Not define in dct_rep'), 
                              regex=True
                             )

print(df)

Output:

      x            y         d    n
0 -17.7    -0.785430  0.053884   y1
1 -15.0 -3820.085000  0.085000  4th
2 -12.5     2.138833  0.143237  3rd
3 -12.4     1.721205  0.251180  3rd
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject