Python 如何打印具有 3 个小数位的 numpy 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22222818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to printing numpy array with 3 decimal places?
提问by Hyman Twain
How can I print numpy array with 3 decimal places? I tried array.round(3)but it keeps printing like this 6.000e-01. Is there an option to make it print like this: 6.000?
如何打印具有 3 个小数位的 numpy 数组?我试过了,array.round(3)但它一直这样打印6.000e-01。有没有一个选项可以让它像这样打印:6.000?
I got one solution as print ("%0.3f" % arr), but I want a global solution i.e. not doing that every time I want to check the array contents.
我得到了一个解决方案print ("%0.3f" % arr),但我想要一个全局解决方案,即每次我想检查数组内容时都不要这样做。
采纳答案by M4rtini
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
This will set numpy to use this lambda function for formatting every float it prints out.
这将设置 numpy 使用这个 lambda 函数来格式化它打印出的每个浮点数。
other types you can define formatting for (from the docstring of the function)
您可以定义格式的其他类型(来自函数的文档字符串)
- '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'
回答by Salvador Dali
Actually what you need is np.set_printoptions(precision=3). There are a lot of helpful other parameters there.
其实你需要的是np.set_printoptions(precision=3)。那里有很多有用的其他参数。
For example:
例如:
np.random.seed(seed=0)
a = np.random.rand(3, 2)
print a
np.set_printoptions(precision=3)
print a
will show you the following:
将向您展示以下内容:
[[ 0.5488135 0.71518937]
[ 0.60276338 0.54488318]
[ 0.4236548 0.64589411]]
[[ 0.549 0.715]
[ 0.603 0.545]
[ 0.424 0.646]]
回答by Thomas
An easier solution is to use numpy around.
一个更简单的解决方案是使用 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]]

