如果我有这样的numpy数组:
[2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]
如何移动小数点并格式化数字,以便最终得到像这样的numpy数组:
[21.53, 8.13, 3.97, 10.08]
np.around(a, decimals=2)
只给了我[2.15300000e+01, 8.13000000e+00, 3.97000000e+00, 1.00800000e+01]
我不想要的东西,我还没有找到另一种方法。
答案 0 :(得分:62)
为了以任意格式制作numpy display float数组,您可以定义一个自定义函数,该函数将float值作为输入并返回格式化字符串:
In [1]: float_formatter = lambda x: "%.2f" % x
这里f
表示定点格式(不是'科学'),.2
表示两位小数(您可以阅读有关字符串格式here的更多信息)。
让我们用浮点值测试它:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
要以这种方式numpy打印所有浮点数组,可以将formatter=
参数传递给np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
现在numpy将以这种方式打印所有浮点数组:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
请注意,这只会影响numpy数组,而不会影响标量:
In [5]: np.pi
Out[5]: 3.141592653589793
它也不会影响非浮点数,复杂的浮点数等 - 您需要为其他标量类型定义单独的格式化程序。
您还应该知道, only 会影响numpy如何显示浮点值 - 计算中使用的实际值将保持其原始精度。
例如:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy打印a
,好像它等于0
,但它不是 - 它仍然等于1E-9
。
如果您确实希望以影响计算方式的方式对数组中的值进行舍入,则应使用np.round
,正如其他人已经指出的那样。
答案 1 :(得分:28)
您会混淆实际精度和显示精度。十进制舍入不能完全用二进制表示。你应该试试:
> np.set_printoptions(precision=2)
> np.array([5.333333])
array([ 5.33])
答案 2 :(得分:24)
您可以使用圆形功能。这里有一些例子
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
如果你想改变只显示表示,我会不建议全局改变打印格式,如上所述。我会将输出格式化。
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print [ "{:0.2f}".format(x) for x in a ]
['21.53', '8.13', '3.97', '10.08']
答案 3 :(得分:1)
[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]