如何将numpy数组从“float64”转换为“float”

2024-04-25 23:40:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将numpy{}从类型'float64'转换为类型'float'?具体来说,我如何用dtype{}将整个array转换成dtype{}?这可能吗?上述重复问题中标量的答案并不能解决我的问题。

考虑一下:

>>> type(my_array[0])
<type 'numpy.float64'>

>>> # Let me try to convert this to 'float':
>>> new_array = my_array.astype(float)
>>> type(new_array[0])
<type 'numpy.float64'>

>>> # No luck.  What about this:
>>> new_array = my_array.astype('float')
>>> type(new_array[0])
<type 'numpy.float64'>

>>> # OK, last try:
>>> type(np.inf)
<type 'float'>
>>> # Yeah, that's what I want.
>>> new_array = my_array.astype(type(np.inf))
>>> type(new_array[0])
<type 'numpy.float64'>

如果您不确定我为什么要这样做,请参阅this question及其答案。


Tags: to答案numpy类型newmytypenp
2条回答

您可以创建一个匿名类型float,如下所示

>>> new_array = my_array.astype(type('float', (float,), {}))
>>> type(new_array[0])
<type 'float'>

是的,实际上当您使用Python的本机float指定数组的数据类型时,numpy会将其转换为float64。如documentation -所示

Note that, above, we use the Python float object as a dtype. NumPy knows that int refers to np.int_, bool means np.bool_ , that float is np.float_ and complex is np.complex_. The other data-types do not have Python equivalents.

以及-

float_ - Shorthand for float64.

这就是为什么即使使用float将整个数组转换为float,它仍然使用np.float64

根据另一个问题的要求,最好的解决方案是将每个标量值取为-

float(new_array[0])

我可以想到的一个解决方案是为float创建一个子类并将其用于强制转换(尽管对我来说这看起来很糟糕)。但如果可能的话,我更喜欢前面的解决方案。示例-

In [20]: import numpy as np

In [21]: na = np.array([1., 2., 3.])

In [22]: na = np.array([1., 2., 3., np.inf, np.inf])

In [23]: type(na[-1])
Out[23]: numpy.float64

In [24]: na[-1] - na[-2]
C:\Anaconda3\Scripts\ipython-script.py:1: RuntimeWarning: invalid value encountered in double_scalars
  if __name__ == '__main__':
Out[24]: nan

In [25]: class x(float):
   ....:     pass
   ....:

In [26]: na_new = na.astype(x)


In [28]: type(na_new[-1])
Out[28]: float                           #No idea why its showing float, I would have thought it would show '__main__.x' .

In [29]: na_new[-1] - na_new[-2]
Out[29]: nan

In [30]: na_new
Out[30]: array([1.0, 2.0, 3.0, inf, inf], dtype=object)

相关问题 更多 >