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

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

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

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

最佳答案

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

为了防止从 float 末尾剥离零:

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]

https://stackoverflow.com/questions/2891790/

相关文章:

python - 在 Python 中打印多个参数

python - 得到一系列列表的笛卡尔积?

python - pandas:使用运算符链接过滤 DataFrame 的行

python - 在 Python 中将 datetime.date 转换为 UTC 时间戳

python - '太多的值无法解包',迭代一个字典。键=>字符串,值=>列表

python - 为什么使用 argparse 而不是 optparse?

python - 为什么 'x' 中的 ('x' 比 'x' == 'x' 快?

python - 动态打印一行

python - 如何计算 ndarray 中某个项目的出现次数?

python - 如何将本地时间字符串转换为 UTC?