如何从' float64'转换numpy数组?到'漂浮'

时间:2015-09-16 04:19:03

标签: python arrays numpy types casting

如何将numpy array'float64'类型转换为'float'类型?具体来说,如何将{strong> 整个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'>

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

3 个答案:

答案 0 :(得分:7)

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

中所述
  

注意,在上面,我们使用Python float对象作为dtype。 NumPy知道int表示np.int_bool表示np.bool_float表示np.float_complex表示np.complex_ float 即可。其他数据类型没有Python等价物。

和 -

  

float _ - float64的简写。

这就是为什么即使你使用np.float64将整个数组转换为float,它仍然使用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) 创建一个子类并将其用于转换(虽然对我而言看起来很糟糕)。但如果可能的话,我更倾向于先前的解决方案。示例 -

#

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

如果您试图停留在numpy中,这不是一个好主意,但是如果您已完成计算并移入本机python,则可以使用

ndarray.tolist()

这会将数组转换为适当的本机类型的列表。它也适用于numpy标量值。