关于python:如何将numpy数组从’float64’转换为’float’

How to convert a numpy array from 'float64' to 'float'

如何将numpy array从类型'float64'转换为类型'float'? 具体来说,如何将整个arraydtype 'float64'转换为dtype 'float'? 这可能吗? 上面被认为是重复的问题中标量的答案没有解决我的问题。

考虑一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> 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'>

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


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

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的原因。

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

1
float(new_array[0])

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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)


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

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

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

1
ndarray.tolist()

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