Replace all instances of a value to another specific value

Question:

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
Asked By: Peter M

||

Answers:

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.

Answered By: pavi2410

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
Answered By: I'mahdi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.