如何在没有科学符号和给定精度的情况下漂亮地打印numpy.array?

2024-04-19 13:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我很好奇,是否有任何方法可以打印格式化的numpy.arrays,例如,以类似的方式:

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

如果我想打印浮点的numpy.array,它会打印几个小数,通常是“科学”格式,即使是低维数组也很难读取。然而,numpy.array显然必须作为字符串打印,即使用%s。有解决办法吗?


Tags: 方法字符串numpy格式方式科学数组array
3条回答

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

有关其他选项,请参见docs for set_printoptions


要使用NumPy 1.15.0或更高版本在本地应用打印选项,可以使用numpy.printoptions上下文管理器。 例如,在with-suiteprecision=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]

联合国大学给出了一个非常完整的答案(他们也从我这里得到了+1),但这里有一个低技术的替代方案:

>>> 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']

您可以从np.array_str命令获得np.set_printoptions功能的子集,该命令仅适用于单个print语句。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html

例如:

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. ]]

相关问题 更多 >