Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression in python to replace last two digits of a column value where if last two digits are 30 then replace it with 50

I have the following data frame

abc=pd.DataFrame()

abc['Col_A']=[1900,1200,1230,1130,1300,0330]
abc

    Col_A
0   1900
1   1200
2   1230
3   1130
4   1300
5   0330

from the above data frame I want to replace last two digits wherever I see 30 I want to replace it with 50

My expected output is below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    Col_A
0   1900
1   1200
2   1250
3   1150
4   1300
5   0350

If not re than anything other than Regular expression will also be helpful.
Thanks in advance

>Solution :

Assuming your Col_A values are actually strings, then we can use str.replace here:

df["Col_A"] = df["Col_A"].str.replace(r'30$', '50')

Note that values like 0330 will only retain their leading zeroes in the event that they are strings, and not integers, the latter which don’t actually have any leading zeroes.

To cover the same logic with a numeric column, use:

df["Col_A"] = np.where(df["Col_A"] % 100 == 30, df["Col_A"] + 20, df["Col_A"])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading