I have the following dataset:
meste = pd.DataFrame({'a':['06/33','40/2','05/22']})
a
0 06/33
1 40/2
2 05/22
And I want to remove the leading 0s in the text (06/33 to 6/33 for example). I tried this, without success:
meste['a'] = meste['a'].str.replace(r"(^0?)","")
a
0 06/33
1 40/2
2 05/22
I also tried with meste['a'].str.replace(r"(^0?)","")
, but it doesn’t work. This is the expected result:
a
0 6/33
1 40/2
2 5/22
What I am doing wrong in the regex statement?
1
pandas.Series.str.replace
assumes you’re passing in a string (not a regex) by default. Your program’s looking for the literal string "(^0?)"
, not “start-of-string, then 0, then something else.” Just set the regex flag to True when you call the method so your expression gets parsed correctly:
meste = pd.DataFrame({'a':['06/33','40/2','05/22']})
meste['a'] = meste['a'].str.replace(r"(^0?)", "", regex=True)