格式化漂浮在numpy的阵列 [英] Formatting floats in a numpy array
问题描述
如果我有一个numpy的数组是这样的:
If I have a numpy array like this:
[2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]
我怎么能移动小数点,所以我结束了一个numpy的数组像这样数字的格式:
how can I move the decimal point and format the numbers so I end up with a numpy array like this:
[21.53, 8.13, 3.97, 10.08]
np.around(一,小数= 2)
只给我 [2.15300000e + 01,+ 8.13000000e 00,3.97000000e + 00 ,1.00800000e + 01]
我不希望,我还没有找到另一种方式来做到这一点。
np.around(a, decimals=2)
only gives me [2.15300000e+01, 8.13000000e+00, 3.97000000e+00, 1.00800000e+01]
Which I don't want and I haven't found another way to do it.
推荐答案
为了使numpy的显示以任意格式浮标阵,你可以自定义一个函数,它的浮点值作为其输入并返回一个格式化字符串:
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = lambda x: "%.2f" % x
的˚F
意味着此处定点格式(而不是科学)和 0.2
意味着两小数位(你可以阅读更多关于字符串这里格式化)。
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
让我们来测试它与一个浮点值:
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
要做出numpy的打印所有浮标阵这种方式,你可以通过格式=
参数 np.set_printoptions
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
现在numpy的将打印所有浮标阵是这样的:
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
请注意,这只会影响numpy的阵列,而不是标量:
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
这也不会影响非花车,花车复杂等 - 你需要定义不同的格式化为其他标量类型
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
您也应该知道,这仅影响numpy的显示如何浮动值 - 将在计算中使用将保留其原来的precision的实际值
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
例如:
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
。
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
如果你真的想圆的值的阵列中,影响它们将如何在计算中使用,你应该使用的方式 np.round
,正如其他人已经指出的那样。
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
这篇关于格式化漂浮在numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!