【问题标题】:python csv writer writes array in scientific notationpython csv writer用科学计数法写入数组
【发布时间】:2017-05-01 04:37:46
【问题描述】:

我有一个浮点数矩阵,我试图将其写入 csv 文件,但是 csv 编写器以科学记数法写入,我想将数字保留为原始记数法,我尝试添加“%.2f " % 但导致以下错误:

"TypeError: 只有长度为 1 的数组可以转换为 Python 标量"

for item in string_color_Values:
   avg_color_values = [ float(item) for item in string_color_Values]

array1t = np.array(avg_color_values)
np.savetxt("test.csv", array1t, delimiter=",")

original:

 [ 0.5258  1.    ]
 [ 0.528   1.    ]
 [ 0.5486  1.    ]
 [ 0.5545  1.    ]
 [ 0.732   1.    ]
 [ 0.7872  1.    ]
 [ 1.      1.    ]]

Csv which i obtain:

1.2270000000035e-01,1.0000000000e+00
2.7639999999790e-01,1.0000000000e+00
etc..

【问题讨论】:

  • 你是在用numpysoley写CSV文件吗?你应该只使用csv 模块。
  • 你确定你使用了正确的语法吗:np.savetxt("test.csv", array1l, "%f.2", delimiter=",") 适合我。

标签: python csv


【解决方案1】:

您需要在对np.savetxt 的调用中包含fmt="%g"。这将写入没有尾随零的数字。或者,如果您想要“干净”格式化的数字,您可以使用例如fmt="%.4f"(或您喜欢的任何其他格式)。

import numpy as np
avg_color_Values = np.random.random((10,3))
array1t = np.array(avg_color_Values)
np.savetxt("test.csv", array1t, delimiter=",", fmt = "%g")

默认情况下,np.savetxt 默认格式为%.18e,这将允许写入float64s 而不会丢失精度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多