栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

你可以

set_printoptions
用来设置输出的精度:

import numpy as npx=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. ]

有关其他选项,请参见文档中的s

et_printoptions

要使用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 npimport contextlib@contextlib.contextmanagerdef 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]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404757.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号