Pandas: How to replace an int substring with another value

Viewed 74

I'd like to reduce the first integer in a string by 1

I have the following dataframe:

No              pl.     Expected              
B2bb-hb        0.56     0.35      
F378cq-h1      0.21     0.62   
W30mm2-fpr2    8.17     0.76    
Z51mm1-yu2     2.81     0.91     

I'd like the output to be:

No              pl.     Expected              
B1bb-hb        0.56     0.35      
F377cq-h1      0.21     0.62   
W29mm2-fpr2    8.17     0.76    
Z50mm1-yu2     2.81     0.91  

I tried the following code:

df['No'] = df['No'].str.replace('(\d+)','(\d+)-int(1)')

But I ended up with:

No                       pl.     Expected              
B(\d+)-int(1)b-h         0.56     0.35      
F(\d+)-int(1)cq-h1       0.21     0.62   
W(\d+)-int(1)mm2-fpr2    8.17     0.76    
Z(\d+)-int(1)mm1-yu2     2.81     0.91  

Please how can I edit the code?

Thanks in advance!

2 Answers

One way using pandas.Series.str.replace with lambda and n:

df["No"].str.replace("(\d+)", lambda x: str(int(x.group(1))-1), n=1)

Output:

0        B1bb-hb
1      F377cq-h1
2    W29mm2-fpr2
3     Z50mm1-yu2
Name: No, dtype: object

We can try using str.replace here with a lambda function:

repl = lambda m: m.group(1) + str(int(m.group(2)) - 1) + m.group(3)
df['No'] = df['No'].str.replace(r'^([^\W\d]*?)(\d+)(\w*)\b', repl)
Related