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.

    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 1:

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"])