简体   繁体   English

python 中的正则表达式替换列值的最后两位数字,如果最后两位数字为 30,则将其替换为 50

[英]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从上面的数据框中,我想在看到 30 的地方替换最后两位数字我想用 50 替换它

My expected output is below.我预期的 output 如下。

    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提前致谢

Assuming your Col_A values are actually strings, then we can use str.replace here:假设您的Col_A值实际上是字符串,那么我们可以在这里使用str.replace

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.请注意,像0330这样的值只会在它们是字符串的情况下保留它们的前导零,而不是整数,后者实际上没有任何前导零。

To cover the same logic with a numeric column, use:要使用数字列覆盖相同的逻辑,请使用:

df["Col_A"] = np.where(df["Col_A"] % 30 == 0, df["Col_A"] + 20, df["Col_A"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM