是否有一种方法可以防止将 Pandas 数据帧写入 CSV,而不将字符串格式的数字转换为数字?
假设我有以下数据框:
>>> 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
>>>
我可以确认我的索引不是数字:
>>> print str(d.index.dtype)
object
>>>
但是当我使用 d.to_csv('MyFile.csv')
写入 csv 时,索引会转换为整数,并且丢失前导 0。有什么建议吗?
最佳答案
d.to_csv('MyFile.csv') 没有问题
。通过运行您的代码,我的 .csv 文件中的所有零都已存在。
如果您使用 d1 = pd.read_csv('MyFile.csv', index_col=0)
,则 d1
中的前导零将被删除。
关于python - Pandas 写入 CSV 指定 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502846/