以给定精度美化打印NumPy数组,不使用科学计数法

471 投票
14 回答
621392 浏览
提问于 2025-04-15 23:02

我想知道怎么打印格式化的NumPy数组,像这样:

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

如果我想打印一个浮点数的numpy.ndarray,它会显示很多小数,通常还会用'科学计数法'的方式,这样即使是低维数组也很难看懂。不过,numpy.ndarray似乎只能以字符串的形式打印,也就是用%s。有没有什么解决办法呢?

14 个回答

46

Unutbu 给出了一个非常完整的回答(我也给了他们一个赞),不过这里有一个简单的替代方案:

>>> x=np.random.randn(5)
>>> x
array([ 0.25276524,  2.28334499, -1.88221637,  0.69949927,  1.0285625 ])
>>> ['{:.2f}'.format(i) for i in x]
['0.25', '2.28', '-1.88', '0.70', '1.03']

作为一个函数(使用 format() 语法来格式化):

def ndprint(a, format_string ='{0:.2f}'):
    print [format_string.format(v,i) for i,v in enumerate(a)]

用法:

>>> ndprint(x)
['0.25', '2.28', '-1.88', '0.70', '1.03']

>>> ndprint(x, '{:10.4e}')
['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']

>>> ndprint(x, '{:.8g}')
['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']

在格式字符串中可以访问数组的索引:

>>> ndprint(x, 'Element[{1:d}]={0:.2f}')
['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']
78

使用 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. ]]
769

使用 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]

撰写回答