漂亮地打印一个没有科学记数法和给定精度的 NumPy 数组

新手上路,请多包涵

如何以类似于以下方式打印格式化的 NumPy 数组:

 x = 1.23456
print('%.3f' % x)

如果我想打印 numpy.ndarray 的浮点数,它会打印几个小数,通常采用“科学”格式,即使对于低维数组也很难阅读。但是, numpy.ndarray 显然必须打印为字符串,即 %s 。有解决方案吗?

原文由 camillio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

使用 numpy.set_printoptions 设置输出的精度:

 import numpy as np
x = np.random.random(10)
print(x)
# [ 0.07837821  0.48002108  0.41274116  0.82993414  0.77610352  0.1023732
#   0.51303098  0.4617183   0.33487207  0.71162095]

np.set_printoptions(precision=3)
print(x)
# [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]

suppress 禁止对小数使用科学记数法:

 y = np.array([1.5e-10, 1.5, 1500])
print(y)
# [  1.500e-10   1.500e+00   1.500e+03]

np.set_printoptions(suppress=True)
print(y)
# [    0.      1.5  1500. ]


要在本地应用打印选项,使用 NumPy 1.15.0 或更高版本,您可以使用 numpy.printoptions 上下文管理器。例如,在 with-suite precision=3suppress=True 设置:

 x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

但在 with-suite 之外,打印选项恢复为默认设置:

 print(x)
# [ 0.07334334  0.46132615  0.68935231  0.75379645  0.62424021  0.90115836
#   0.04879837  0.58207504  0.55694118  0.34768638]

如果您使用的是早期版本的 NumPy,您可以自己创建上下文管理器。例如,

 import numpy as np
import contextlib

@contextlib.contextmanager
def printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    try:
        yield
    finally:
        np.set_printoptions(**original)

x = np.random.random(10)
with printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]


为了防止从浮点数的末尾剥离零:

np.set_printoptions 现在有一个 formatter 参数,允许您为每种类型指定格式函数。

 np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)

哪个打印

[ 0.078  0.480  0.413  0.830  0.776  0.102  0.513  0.462  0.335  0.712]

代替

[ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]

原文由 unutbu 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 np.array_str 仅将格式应用于单个打印语句。它给出了 np.set_printoptions 的功能的一个子集。

例如:

 In [27]: x = np.array([[1.1, 0.9, 1e-6]] * 3)

In [28]: print(x)
[[  1.10000000e+00   9.00000000e-01   1.00000000e-06]
 [  1.10000000e+00   9.00000000e-01   1.00000000e-06]
 [  1.10000000e+00   9.00000000e-01   1.00000000e-06]]

In [29]: print(np.array_str(x, precision=2))
[[  1.10e+00   9.00e-01   1.00e-06]
 [  1.10e+00   9.00e-01   1.00e-06]
 [  1.10e+00   9.00e-01   1.00e-06]]

In [30]: print(np.array_str(x, precision=2, suppress_small=True))
[[ 1.1  0.9  0. ]
 [ 1.1  0.9  0. ]
 [ 1.1  0.9  0. ]]

原文由 Daniel Golden 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题