Home > Enterprise >  How to save numbers as text when exporting a pandas dataframe
How to save numbers as text when exporting a pandas dataframe

Time:01-02

I have a * .csv file, with data in a field of this type: 00123, 0145, 0004567, that is, with leading zeros (text type); the case ,,, is that I want to save them in another dataframe (after other calculations) ,, and I would like to keep those zeros; but no matter how hard I look, it always converts them without zeros ,,, the ones above, would be: 123,145,4567. I have converted just in case with dtypes to str ,,, but it does nothing. ff1 = pd.read_csv (dir "\ lotr \ dats \ coinc4f.csv") ff1.POSIF = ff1.POSIF.astype (str)

How could I keep the first format, which is the one that interests me? type 0000xxx.

Thanks a lot

CodePudding user response:

Pandas is likely not responsible for the loss of the trailing zeros.

Are the zeros there when you check the output file with a text editor?

Here is a quick snippet demonstrating they the zeros are preserved. It is using io.StringIO to stimulate files.

import pandas as pd
import io

t='''00123, 0145, 0004567
1,2,3'''
df = pd.read_csv(io.StringIO(t))

out = io.StringIO()
df.to_csv(out, index=False)

print(out.getvalue())

output:

00123, 0145, 0004567
1,2,3
  • Related