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

Python 如何在没有科学符号和给定精度的情况下漂亮地打印numpy.array?,python,numpy,python-2.x,pretty-print,Python,Numpy,Python 2.x,Pretty Print,我很好奇,是否有任何方法可以打印格式化的numpy.array,例如,以类似以下的方式: x = 1.23456 print '%.3f' % x 如果我想打印浮点的numpy.array,它会打印几个小数,通常是“科学”格式,即使是低维数组也很难读取。但是,numpy.array显然必须作为字符串打印,即使用%s。有解决办法吗 您可以使用设置打印选项设置输出精度: import numpy as np x=np.random.random(10) print(x) # [ 0.0783782

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

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

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

您可以使用
设置打印选项
设置输出精度:

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或更高版本在本地应用打印选项,可以使用上下文管理器。 例如,在带套件的
中设置了
精度=3
抑制=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]
但在带套件的
之外,打印选项将返回默认设置:

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\u 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给出了一个非常完整的答案(他们也从我这里得到了+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()
语法进行格式化):

用法:

>>> 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.set_printoptions( threshold=20, edgeitems=10, linewidth=140,
    formatter = dict( float = lambda x: "%.3g" % x ))  # float arrays %.3g

numpy阵列的打印F(“…%.3g…%.1f…”,arg,arg…) 例子: printf(““”x:%.3g A:%.1f s:%s B:%s”“, x、 A,“str”,B) 如果'x'和'A'是数字,这就像python中的`“格式”%(x,A,“str”,B)`。 如果它们是numpy数组,则每个元素都以其自己的格式打印: `x`:e.g.[1.23 1.23e-6…]3位数字 `A`:[[1位小数点后…]] 使用当前的'np.set_printoptions()`。例如,与 np.设置打印选项(阈值=100,边缘项=3,抑制项=True) 只打印大“x”和“A”的边缘。 `B`打印为'str(B)`,对于任何'B`--一个数字、一个列表、一个numpy对象。。。 `printf()`试图理智地处理太少或太多的参数, 但这是不确定的,可能会改变。 工作原理: numpy有一个函数'np.array2string(a,“%.3g”)`(简化了一点)。 `printf()`拆分格式字符串,并对格式/参数对进行拆分 格式:%d e f g arg:试试'np.asanyarray()` -->%s np.array2string(参数,格式) 其他格式和非ndarray参数将保持不变,格式与往常一样。 笔记: `printf(…end=file=)`被传递给python`print()`函数。 仅实现格式`%[可选宽度.精度]d e f g`, 不是“%(varname)格式”。 %d截断浮点数,例如0.9和-0.9到0;%。0轮,0.9比1。 %g与%.6g相同,6位。 %%是单个“%”字符。 函数`sprintf()`返回一个长字符串。例如 title=sprintf(“%s m%g n%g X%.3g”, __文件(m,n,X) 印刷品(标题) ... 标题(标题) 模块全局: _fmt=“%.3g”#额外参数的默认值 _挤压(n,1)(1,n)->(n,n)打印一行而不是n 另见: http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html http://docs.python.org/2.7/library/stdtypes.html#string-格式化 ''' # http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array #............................................................................... 来自“未来”导入部门的“打印”功能 进口稀土 将numpy作为np导入 __版本=“2014-02-03二月丹尼斯” _splitformat=re.compile(r''( %
(?以下是我使用的,它非常简单:

print(np.vectorize("%.2f".__mod__)(sparse))

也可能有用,具体取决于应用程序的详细信息,例如:
numpy.char.mod('Value=%4.2f',numpy.arange(5,10,0.1))
将返回一个包含元素“Value=5.00”,“Value=5.10”等的字符串数组(作为一个有点做作的示例).

您可以从
np.array\u str
命令获得
np.set\u 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. ]]
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]
import numpy as np
np.set_printoptions(suppress=True)
a3 = 4E-3
a4 = 4E-4
a5 = 4E-5
a6 = 4E-6
a7 = 4E-7
a8 = 4E-8
#--first, display separate numbers-----------
print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
#---second, display a list using a loop----------
myList = [a3,a4,a5,a6,a7,a8]
print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
for x in myList: 
    print('{:9.5f}'.format(x), end='')
print()
#---third, display a numpy array using a loop------------
myArray = np.array(myList)
print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
for x in myArray:
    print('{:9.5f}'.format(x), end='')
print()

我经常希望不同的列具有不同的格式。下面是我如何通过将NumPy数组的(切片)转换为元组,使用不同的格式打印简单的2D数组:

import numpy as np
dat = np.random.random((10,11))*100  # Array of random values between 0 and 100
print(dat)                           # Lines get truncated and are hard to read
for i in range(10):
    print((4*"%6.2f"+7*"%9.4f") % tuple(dat[i,:]))

denis answer中隐藏着一块宝石,它让我们很容易获得字符串形式的结果(在今天的numpy版本中):


另一个选项是使用
十进制
模块:

import numpy as np
from decimal import *

arr = np.array([  56.83,  385.3 ,    6.65,  126.63,   85.76,  192.72,  112.81, 10.55])
arr2 = [str(Decimal(i).quantize(Decimal('.01'))) for i in arr]

# ['56.83', '385.30', '6.65', '126.63', '85.76', '192.72', '112.81', '10.55']

很惊讶没有看到所提到的
方法-这意味着不会干扰打印选项

import numpy as np

x = np.random.random([5,5])
print(np.around(x,decimals=3))

Output:
[[0.475 0.239 0.183 0.991 0.171]
 [0.231 0.188 0.235 0.335 0.049]
 [0.87  0.212 0.219 0.9   0.3  ]
 [0.628 0.791 0.409 0.5   0.319]
 [0.614 0.84  0.812 0.4   0.307]]

numpy数组具有方法
round(precision)
,该方法返回一个新的numpy数组,并相应地对元素进行取整

import numpy as np

x = np.random.random([5,5])
print(x.round(3))
FYI Numpy 1.15(发布日期待定)将。这意味着以下内容将与中的相应示例(由unutbu和Neil G)相同,而无需编写自己的上下文管理器。例如,使用他们的示例:

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. ]]
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]
import numpy as np
np.set_printoptions(suppress=True)
a3 = 4E-3
a4 = 4E-4
a5 = 4E-5
a6 = 4E-6
a7 = 4E-7
a8 = 4E-8
#--first, display separate numbers-----------
print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
#---second, display a list using a loop----------
myList = [a3,a4,a5,a6,a7,a8]
print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
for x in myList: 
    print('{:9.5f}'.format(x), end='')
print()
#---third, display a numpy array using a loop------------
myArray = np.array(myList)
print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
for x in myArray:
    print('{:9.5f}'.format(x), end='')
print()

我发现,当使用循环显示列表或数组时,通常的浮点格式{:9.5f}可以正常工作——抑制小值电子符号。但是,当格式化程序在一个打印语句中有多个项时,该格式有时无法抑制其电子符号。例如:

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. ]]
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]
import numpy as np
np.set_printoptions(suppress=True)
a3 = 4E-3
a4 = 4E-4
a5 = 4E-5
a6 = 4E-6
a7 = 4E-7
a8 = 4E-8
#--first, display separate numbers-----------
print('Case 3:  a3, a4, a5:             {:9.5f}{:9.5f}{:9.5f}'.format(a3,a4,a5))
print('Case 4:  a3, a4, a5, a6:         {:9.5f}{:9.5f}{:9.5f}{:9.5}'.format(a3,a4,a5,a6))
print('Case 5:  a3, a4, a5, a6, a7:     {:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7))
print('Case 6:  a3, a4, a5, a6, a7, a8: {:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5}{:9.5f}'.format(a3,a4,a5,a6,a7,a8))
#---second, display a list using a loop----------
myList = [a3,a4,a5,a6,a7,a8]
print('List 6:  a3, a4, a5, a6, a7, a8: ', end='')
for x in myList: 
    print('{:9.5f}'.format(x), end='')
print()
#---third, display a numpy array using a loop------------
myArray = np.array(myList)
print('Array 6: a3, a4, a5, a6, a7, a8: ', end='')
for x in myArray:
    print('{:9.5f}'.format(x), end='')
print()
我的结果显示了案例4、5和6中的错误:

Case 3:  a3, a4, a5:               0.00400  0.00040  0.00004
Case 4:  a3, a4, a5, a6:           0.00400  0.00040  0.00004    4e-06
Case 5:  a3, a4, a5, a6, a7:       0.00400  0.00040  0.00004    4e-06  0.00000
Case 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000    4e-07  0.00000
List 6:  a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
Array 6: a3, a4, a5, a6, a7, a8:   0.00400  0.00040  0.00004  0.00000  0.00000  0.00000
对此我没有任何解释,因此我总是使用一个循环来浮动多个值的输出。

我使用

def np_print(array,fmt="10.5f"):
    print (array.size*("{:"+fmt+"}")).format(*array)

对多维数组进行修改并不困难。

有没有方法应用f