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

Time:07-08

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

CodePudding user response:

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
  • Related