Skip to content
Advertisement

Trim leading zero’s using python pandas without changing the datatype of any columns

I have a csv file of around 42000 lines and around 80 columns, from which I need to remove leading Zero’s, hence I am using Pandas to_csv and saving it back to text file by which leading Zero’s are removed.

Any column may contain null values in any row, but those columns are getting converted to Float datatype and getting decimal values as output, I want to avoid that scenario.

For example, below is a sample of my original file.

JavaScript

I used the below method to convert to

JavaScript

The output file looks like

JavaScript

It has removed all the leading Zero’s in all the columns as expected, however, at the last column, it is converting to float with decimal values as that column has got null values. Any idea on how can this be rectified?

Advertisement

Answer

First convert all values to strings and in next step remove trailing zeros:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement