简体   繁体   English

使用 pandas read_csv 时保持准确的数据格式

[英]keep exact data format when using pandas read_csv

I am reading csv file with pd.read_csv containing any kind of number format.我正在阅读 csv 文件,其中 pd.read_csv 包含任何类型的数字格式。 All is fine, except numbers with scientific notation like -6.15000000000001E-02 are converted to float like -0.0615000000000001.一切都很好,除了像 -6.15000000000001E-02 这样的科学记数法的数字被转换为像 -0.0615000000000001 这样的浮点数。 Unfortunately, I need to keep the same format as in the original csv file, even the 'E' has to be kept capital.不幸的是,我需要保持与原始 csv 文件相同的格式,即使是“E”也必须保持大写。 Hope the request is clear and somebody can find a solution.希望请求很明确,有人可以找到解决方案。 Thanks谢谢

Use dtype argument.使用dtype参数。 From pd.read_csv docs:来自pd.read_csv文档:

dtypeType name or dict of column -> type, optional Data type for data or columns. dtypeType name or dict of column -> type, optional 数据或列的数据类型。 Eg {'a': np.float64, 'b': np.int32, 'c': 'Int64'} Use str or object together with suitable na_values settings to preserve and not interpret dtype.例如 {'a': np.float64, 'b': np.int32, 'c': 'Int64'} 使用 str 或 object 以及合适的 na_values 设置来保留而不是解释 dtype。 If converters are specified, they will be applied INSTEAD of dtype conversion.如果指定了转换器,则将应用它们代替 dtype 转换。

test.csv:测试.csv:

a,b
1,-6.15000000000001E-02
print(pd.read_csv('test.csv', dtype={'b': str}))

This outputs这输出

   a                      b
0  1  -6.15000000000001E-02

Just keep in mind that the b column is now a string and not a number.请记住, b列现在是字符串而不是数字。 It will need to be explicitly converted before any attempt of doing any computation with it,在尝试对其进行任何计算之前,需要对其进行显式转换,

Use dtype = str in your import could work:在您的导入中使用 dtype = str 可以工作:

df = pd.read_csv('filename', dtype = str)

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

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