【问题标题】:How to round a numpy stacked array when written to file?写入文件时如何舍入 numpy 堆叠数组?
【发布时间】:2015-05-14 16:54:01
【问题描述】:

我正在尝试使用 numpy.column_stack 将多个数组写入文件,但我无法将其四舍五入到小数点后两位。这是可重现的代码:

import numpy as np
A = np.array([1.1334, 4.10343, 12.4343])
B = np.array([2.1334, 5.12343, 16.23543])
C = np.array([4.1334, 4.3563, 18.36343])
np.savetxt('data.dat', np.around(np.column_stack((A, B, C)), decimals=2))

输出

1.129999999999999893e+00 2.129999999999999893e+00 4.129999999999999893e+00
4.099999999999999645e+00 5.120000000000000107e+00 4.360000000000000320e+00
1.242999999999999972e+01 1.623999999999999844e+01 1.835999999999999943e+01

简而言之,我想将条目四舍五入到小数点后两位,是否可以使用这种方法来分隔条目。

【问题讨论】:

    标签: python arrays numpy file-writing


    【解决方案1】:

    您需要在savetext 函数中使用具有正确格式的fmt 标志,因此在savetext 中添加fmt='%.2f',并且为了获得更优雅的结果,您也可以指定delimiter 标志:

    np.savetxt('data.dat', np.around(np.column_stack((A, B, C)), decimals=2),fmt='%.2f',delimiter='\t')
    

    结果:

    1.13    2.13    4.13
    4.10    5.12    4.36
    12.43   16.24   18.36
    

    numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')

    将数组保存到文本文件中。

    【讨论】:

      【解决方案2】:

      你需要指定格式到np.savetxt

      np.savetxt('data.dat', np.around(np.column_stack((A, B, C)), decimals=2), fmt="%.2f")
      

      【讨论】:

      • 这也是 OP 需要的! ;)
      猜你喜欢
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2014-09-12
      相关资源
      最近更新 更多