如何在没有科学符号和给定精度的情况下漂亮地打印numpy.Array?我很好奇,有没有办法打印格式化的numpy.arrays,例如,以类似的方式:x = 1.23456print '%.3f' % x如果我想打印numpy.array在浮标中,它打印了几个小数,通常是“科学”格式,即使对于低维数组,也很难读懂。然而,numpy.array显然必须以字符串的形式打印,即用%s..有解决办法吗?
3 回答
紫衣仙女
TA贡献1839条经验 获得超15个赞
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. ]
在本地应用打印选项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]
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]
添加回答
举报
0/150
提交
取消