AJG519
AJG519

Reputation: 3379

Pandas write to CSV specify dtype

Is there a way to prevent write a Pandas dataframe as a CSV without converting numbers that are formatted as strings to numerics?

Say I have the following dataframe:

>>> import pandas as pd
>>> d=pd.DataFrame(index=['07000','07001','07002'], data=[1,2,3], columns=['Value'])
>>> d.index.name='Zipcode'
>>> d
         Value
Zipcode       
07000        1
07001        2
07002        3
>>> 

I can confirm that my index is not a numeric:

>>> print str(d.index.dtype)
object
>>> 

But when I write to csv using d.to_csv('MyFile.csv') the index is converted to an integer and I lose the leading 0. Any suggestions?

Upvotes: 1

Views: 2895

Answers (1)

cuiqiang1990
cuiqiang1990

Reputation: 19

There is no problem with the d.to_csv('MyFile.csv'). I have all the zeros in my .csv file by running your code.

If you use d1 = pd.read_csv('MyFile.csv', index_col=0), the leading zeros will be dropped in the d1.

Upvotes: 2

Related Questions