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

dbl*_*iss 5 python arrays types casting numpy

如何将numpy arrayfrom类型转换'float64'为type 'float'?具体来说,我怎么转换整个array用dtype 'float64'有dtype 'float'?这可能吗? 在上面的重复思考问题中,标量的答案并没有解决我的问题.

考虑一下:

>>> 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'>
Run Code Online (Sandbox Code Playgroud)

如果您不确定我为什么要这样做,请参阅此问题及其答案.

Ana*_*mar 7

是的,实际上当你使用Python的native float指定数组的dtype时,numpy会将其转换为float64.正如文件中所述 -

注意,在上面,我们使用Python float对象作为dtype.NumPy的人都知道int是指np.int_,bool意味着np.bool_,这float是np.float_和complex是np.complex_.其他数据类型没有Python等价物.

而且 -

float_ - float64的缩写.

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

根据另一个问题的要求,最佳解决方案是在将每个标量值作为 - 后转换为普通浮点对象 -

float(new_array[0])
Run Code Online (Sandbox Code Playgroud)

我能想到的解决方案是创建一个子类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)
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 3

float您可以像这样创建匿名类型

>>> new_array = my_array.astype(type('float', (float,), {}))
>>> type(new_array[0])
<type 'float'>
Run Code Online (Sandbox Code Playgroud)