Skip to content
Advertisement

Remove leading zeroes pandas

For example I have such a data frame

import pandas as pd
nums = {'amount': ['0324','S123','0010', None, '0030', 'SA40', 'SA24']}
df = pd.DataFrame(nums)

enter image description here

And I need to remove all leading zeroes and replace NONEs with zeros:

enter image description here

I did it with cycles but for large frames it works not fast enough. I’d like to rewrite it using vectores

Advertisement

Answer

you can try str.replace

df['amount'].str.replace(r'^(0+)', '').fillna('0')
0     324
1    S123
2      10
3       0
4      30
5    SA40
6    SA24
Name: amount, dtype: object
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement