Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: how to remove leading zeros after string in pandas column?

I have a dataframe that looks like the following

df
     id
0   IT030
1   IT4
2   IT022
3   BE34

I would like to remove all the zeros after the characters and have this

df
     id
0   IT30
1   IT4
2   IT22
3   BE34

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a regex:

# if 0s after a non digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+', r'\1', regex=True)

or:

# if 0s between a non digit and a digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+(\d+)', r'\1\2', regex=True)

output (as new column id2 for clarity):

      id   id2
0  IT030  IT30
1    IT4   IT4
2  IT022  IT22
3   BE34  BE34
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading