Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change values in a string with a particular value using regex?

have a df with values

    0               1 
0 RS 125       | password1
1 EURO 25      | password2
2 DNR 30       | password3

Using regex how to change values of these at once likes the values after RS,EURO,DNR should be replace with 100

output should be

    0               1 
0 RS 100       | password1
1 EURO 100      | password2
2 DNR 100      | password3

Tried this

def Currency(0):

    pattern = re.compile("(Rs |EURO |DNR |)")
    result = pattern.match(name)

Trying to replace the matched ones.

like image 587
艾瑪艾瑪艾瑪 Avatar asked Dec 22 '25 09:12

艾瑪艾瑪艾瑪


1 Answers

You may use

df['col'] = df['col'].str.replace(r'(?i)((?:Rs|EURO|DNR)\s*)\d+', r'\g<1>100')

Or, if you want to match the currency names as whole words, prepend the capturing group with a word boundary \b:

r'(?i)\b((?:Rs|EURO|DNR)\s*)\d+'
      ^^

See this regex demo.

Details

  • (?i) - case insensitive flag
  • ((?:Rs|EURO|DNR)\s*) - Group 1 (\g<1> in the replacement pattern refers to this value):
    • (?:Rs|EURO|DNR) - Rs or EURO or DNR
    • \s* - 0+ whitespaces
  • \d+ - one or more digits

See the regex demo.

like image 87
Wiktor Stribiżew Avatar answered Dec 23 '25 21:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!