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

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

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


当前回答

很惊讶没有看到周围的方法提到-意思是没有搞乱打印选项。

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数组(切片)转换为元组来打印一个简单的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,:]))

gem使它太容易获得字符串形式的结果(在今天的numpy版本中)隐藏在denis answer中: np.array2string

>>> import numpy as np
>>> x=np.random.random(10)
>>> np.array2string(x, formatter={'float_kind':'{0:.3f}'.format})
'[0.599 0.847 0.513 0.155 0.844 0.753 0.920 0.797 0.427 0.420]'

使用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=3和suppress=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现在有一个格式化器参数,允许您为每种类型指定一个格式化函数。

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]

numpy数组有round(precision)方法,该方法返回一个新的numpy数组,其中的元素是四舍五入的。

import numpy as np

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

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