为什么熊猫在写入csv时会删除前导零?

时间:2019-08-09 23:17:52

标签: python python-3.x string pandas csv

我有一个数据框,其中有一列名为“ CBG”的数字作为字符串值。

    CBG             acs_total_persons   acs_total_housing_units
0   010010211001    1925                1013
1   010030114011    2668                1303
2   010070100043    930                 532    

当我将其写入csv文件时,开头的'O'被删除:

combine_acs_merge.to_csv(new_out_csv, sep=',')
>>> CBG: [0: 10010221101, ...]

已经是一个字符串;如何避免在.csv文件中删除前导零

3 个答案:

答案 0 :(得分:1)

Pandas不会去除填充的零。您喜欢在Excel中打开时看到的内容。在诸如notepad ++之类的文本编辑器中打开csv,您将看到它们仍被零填充。

答案 1 :(得分:1)

让我们举个例子:

下面是您的示例DataFrame:

>>> df
    col1   num
0    One   011
1    two  0123
2  three  0122
3   four  0333

num视为可以转换为str()的整数。

>>> df["num"] = df["num"].astype(str)
>>> df.to_csv("datasheet.csv")

输出:

$ cat datasheet.csv

您会发现完整的前导零。

,col1,num
0,One,011
1,two,0123
2,three,0122
3,four,0333

或者,如果您首先从csv中读取数据,请使用belwo。

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")

结果:

$ cat CBG.csv
,CBG,acs_total_housing_units,acs_total_persons
0,010010211001,1013,1925
1,010030114011,1303,2668
2,010070100043,532,930

答案 2 :(得分:1)

读取CSV文件时,pandas尝试将每一列中的值转换为合适的某种数据类型。如果看到仅包含数字的列,它将将该列的dtype设置为int64。这会将“ 010010211001”转换为10010211001。

如果您不希望发生任何数据类型转换,请在读取CSV文件时指定dtype = str。 根据read_csv https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html的熊猫文档:

dtype : Type name or dict of column -> type, optional

    Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Use str or object
    together with suitable na_values settings to preserve and not interpret dtype. If
    converters are specified, they will be applied INSTEAD of dtype conversion.