让我们举个例子:
下面是您的示例数据框:
>>> df
col1 num
0 One 011
1 two 0123
2 three 0122
3 four 0333
考虑到num
作为一个可以转换为的 intstr()
.
>>> df["num"] = df["num"].astype(str)
>>> df.to_csv("datasheet.csv")
Output:
$ 猫数据表.csv
您会发现前导零完好无损。
,col1,num
0,One,011
1,two,0123
2,three,0122
3,four,0333
或者,如果您先从 csv 读取数据,然后使用下面的..
pd.read_csv('test.csv', dtype=str)
但是,如果您的专栏CBG
已经str
那么它应该是直截了当的..
>>> df = pd.DataFrame({'CBG': ["010010211001", "010030114011", "010070100043"],
... 'acs_total_persons': [1925, 2668, 930],
... 'acs_total_housing_units': [1013, 1303, 532]})
>>>
>>> df
CBG acs_total_housing_units acs_total_persons
0 010010211001 1013 1925
1 010030114011 1303 2668
2 010070100043 532 930
>>> df.to_csv("CBG.csv")
result:
$ cat CBG.csv
,CBG,acs_total_housing_units,acs_total_persons
0,010010211001,1013,1925
1,010030114011,1303,2668
2,010070100043,532,930