1

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

  • two ideas: 1) is the field still a string field from the .csv file? *before* you're converting with `.astype(str)`... 2) if you're opening the file with Excel, that's what's removing the leading zeros. can you use something other than Excel to view? – mechanical_meat Dec 28 '21 at 21:08
  • It's not clear what you're asking. Are you bringing the text strings in, treating them as numbers and doing calculations on them, and then trying to restore the leading zeroes? Or are you just trying to carry them through your intervening dataframes as text strings? – G. Anderson Dec 28 '21 at 21:58

1 Answers1

1

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
mozway
  • 194,879
  • 13
  • 39
  • 75