【问题标题】:How to printing numpy array with 3 decimal places? [duplicate]如何打印小数点后 3 位的 numpy 数组? [复制]
【发布时间】:2014-04-08 23:46:20
【问题描述】:

如何打印小数点后 3 位的 numpy 数组?我试过array.round(3),但它一直像这样打印6.000e-01。是否可以选择让它像这样打印:6.000

我有一个解决方案 print ("%0.3f" % arr),但我想要一个全局解决方案,即不是每次我想检查数组内容时都这样做。

【问题讨论】:

  • 你的第一个问题是6.000e-01 != 6.0006.000e-01 == 0.6.
  • 我认为你无法说服 numpy 将 6.000e-01 打印为 6.000 ;-) 也许是 0.600...
  • 试试np.set_printoptions(precision=3)
  • 当你的价值非常小的时候试试np.set_printoptions(precision=3, suppress=True)

标签: python numpy


【解决方案1】:
 np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})

这将设置 numpy 使用这个 lambda 函数来格式化它打印出的每个浮点数。

您可以定义格式的其他类型(来自函数的文档字符串)

    - 'bool'
    - 'int'
    - 'timedelta' : a `numpy.timedelta64`
    - 'datetime' : a `numpy.datetime64`
    - 'float'
    - 'longfloat' : 128-bit floats
    - 'complexfloat'
    - 'longcomplexfloat' : composed of two 128-bit floats
    - 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
    - 'str' : all other strings

Other keys that can be used to set a group of types at once are::

    - 'all' : sets all types
    - 'int_kind' : sets 'int'
    - 'float_kind' : sets 'float' and 'longfloat'
    - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
    - 'str_kind' : sets 'str' and 'numpystr'

【讨论】:

  • 抱歉,我删除了接受。 np.set_printoptions() 不接受格式化程序!
  • 如果它不接受格式化程序,您可能正在运行旧版本的 numpy。我不确定何时添加此功能。但是有文档记录,所以确实支持:docs.scipy.org/doc/numpy/reference/generated/…
  • 值得注意的是,您不需要 lambda:np.set_printoptions(formatter={'float': "{0:0.3f}".format}) 可以工作,因为 format 已经是一个函数。
【解决方案2】:

其实你需要的是np.set_printoptions(precision=3)。有很多helpful other parameters there

例如:

np.random.seed(seed=0)
a = np.random.rand(3, 2)
print a
np.set_printoptions(precision=3)
print a

将向您展示以下内容:

[[ 0.5488135   0.71518937]
 [ 0.60276338  0.54488318]
 [ 0.4236548   0.64589411]]
[[ 0.549  0.715]
 [ 0.603  0.545]
 [ 0.424  0.646]]

【讨论】:

  • 您的示例有效。但我不知道为什么在我的 jupyter notebook 中,它仍然显示类似[ 5.000e-02 2.139e-01 1.028e+00 ..., 1.804e+03 1.805e+03 1.806e+03]
  • 最后,这行得通:np.set_printoptions(precision=3, suppress=True),因为可以抑制小值。参考文档here
【解决方案3】:

一个更简单的解决方案是使用 numpy。

>>> randomArray = np.random.rand(2,2)
>>> print(randomArray)
array([[ 0.07562557,  0.01266064],
   [ 0.02759759,  0.05495717]])
>>> print(np.around(randomArray,3))
[[ 0.076  0.013]
 [ 0.028  0.055]]

【讨论】:

  • 这并不妨碍 numpy 使用科学记数法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
相关资源
最近更新 更多