【问题标题】:Writing floats to csvs in python -- truncation error在 python 中将浮点数写入 csv - 截断错误
【发布时间】:2012-03-13 21:49:56
【问题描述】:

我遇到了浮点数在我的 csv 写入过程中被截断的问题。这很难复制,因为它在数千个文件中很少发生,但我需要针对它进行保护。以下是代码的示例:

import csv
import numpy as np
x = np.random.normal(0, .001, 1000).tolist()
draws_header = ['draw%s'%(x) for x in range(1000)]
final_output = np.array(x)
outfile = open('filepath.csv', 'w')
writer = csv.writer('filepath')
writer.writerow(first_row)
writer.writerows(final_output)
outfile.close()

根据输出(其中所有数字必须小于 1),看起来小数字中的最后一个字符(即“...e-5”)正在丢失:

draw373         draw374         draw375          draw376    
0.000744        0.003008        0.001566         9.727522

关于如何防止这种情况的任何建议?

【问题讨论】:

    标签: python csv floating-point truncate


    【解决方案1】:

    我建议为此使用 numpy 的 csv 编写器。例如:

    >>> import numpy as np
    >>> x = np.random.normal(0, .001, 1000)
    >>> draws_header = ['draw%s'%(i) for i in range(1000)]
    >>> f = open('file.csv', 'w')
    >>> np.savetxt(f, np.array(draws_header)[:,None].T, fmt="%s", delimiter="\t")
    >>> np.savetxt(f, x[:,None].T, delimiter="\t")
    >>> f.close()
    

    这会正确地序列化数字。您还可以将格式字符串传递给 savetxt 以指定如何打印浮点值。

    【讨论】:

    • 感谢您的提示 - 我会试一试。
    • 很好的答案,但是这样会更干净:>>> np.savetxt(f, np.array([draws_header]), fmt="%s", delimiter="\t" ) >>> np.savetxt(f, [x], delimiter="\t")
    【解决方案2】:

    问题在于数字的十进制表示和内存表示之间的转换。

    您可以获取有关 float 的 python 实现的更多详细信息: http://docs.python.org/library/sys.html#sys.float_info

    还有关于浮点的综合教程: http://docs.python.org/tutorial/floatingpoint.html

    特别推荐你“表示错误”部分

    #input
    a = 0
    for x in xrange(10):
      a += 0.1
    print a   
    #output
    0.9999999999999999
    

    如果您的应用程序需要高精度,您可以使用:

    #input
    from decimal import Decimal
    a = Decimal('0.0')
    for x in xrange(10):
      a += Decimal('0.1')
    print a
    #output
    1.0
    

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 2011-04-29
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多