简体   繁体   English

导出 pandas dataframe 时如何将数字另存为文本

[英]How to save numbers as text when exporting a pandas dataframe

I have a *.csv file, with data in a field of this type: 00123, 0145, 0004567, that is, with leading zeros (text type);我有一个 *.csv 文件,数据在这种类型的字段中:00123、0145、0004567,即带有前导零(文本类型); the case,,, is that I want to save them in another dataframe (after other calculations),, and I would like to keep those zeros;情况是,我想将它们保存在另一个 dataframe 中(经过其他计算),并且我想保留这些零; but no matter how hard I look, it always converts them without zeros,,, the ones above, would be: 123,145,4567.但无论我看起来多么努力,它总是将它们转换为不带零的,,上面的那些,将是:123,145,4567。 I have converted just in case with dtypes to str,,, but it does nothing.我已经将 dtypes 转换为 str,,,但它什么也没做。 ff1 = pd.read_csv (dir + "\ lotr \ dats \ coinc4f.csv") ff1.POSIF = ff1.POSIF.astype (str) 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.输入 0000xxx。

Thanks a lot非常感谢

Pandas is likely not responsible for the loss of the trailing zeros. Pandas 可能不对尾随零的丢失负责。

Are the zeros there when you check the output file with a text editor ?当您使用文本编辑器检查 output 文件时,是否有零?

Here is a quick snippet demonstrating they the zeros are preserved.这是一个快速片段,演示它们保留了零。 It is using io.StringIO to stimulate files.它使用io.StringIO来刺激文件。

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: output:

00123, 0145, 0004567
1,2,3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM