如何打印三位小数的numpy数组?
我想知道怎么把numpy数组打印成小数点后有三位数字的样子。我试过用array.round(3)
,但是它总是打印成这样6.000e-01
。有没有什么方法可以让它打印成6.000
的样子?
我找到一个解决办法是用print ("%0.3f" % arr)
,但是我想要一个全局的解决方案,也就是说我不想每次查看数组内容的时候都要这样做。
3 个回答
34
一个更简单的解决办法是使用numpy这个库。
>>> randomArray = np.random.rand(2,2)
>>> print(randomArray)
array([[ 0.07562557, 0.01266064],
[ 0.02759759, 0.05495717]])
>>> print(np.around(randomArray,3))
[[ 0.076 0.013]
[ 0.028 0.055]]
49
其实你需要的是 np.set_printoptions(precision=3)
。这里有很多其他有用的参数可以参考,具体可以查看这个链接。
比如说:
np.random.seed(seed=0)
a = np.random.rand(3, 2)
print a
np.set_printoptions(precision=3)
print a
这段代码会给你显示以下内容:
[[ 0.5488135 0.71518937]
[ 0.60276338 0.54488318]
[ 0.4236548 0.64589411]]
[[ 0.549 0.715]
[ 0.603 0.545]
[ 0.424 0.646]]
77
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
- 'bool'
- 'int'
- 'timedelta' : a `numpy.timedelta64`
- 'datetime' : a `numpy.datetime64`
- 'float'
- 'longfloat' : 128-bit floats
- 'complexfloat'
- 'longcomplexfloat' : composed of two 128-bit floats
- 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
- 'str' : all other strings
Other keys that can be used to set a group of types at once are::
- 'all' : sets all types
- 'int_kind' : sets 'int'
- 'float_kind' : sets 'float' and 'longfloat'
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
- 'str_kind' : sets 'str' and 'numpystr'
这段话的意思是,这样做会让numpy在打印每个浮点数的时候,使用这个自定义的lambda函数来格式化输出。
你还可以为其他类型定义格式化方式(这个信息来自于函数的文档说明)。