How to convert a numpy array from 'float64' to '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的本机
Note that, above, we use the Python float object as a dtype. NumPy knows that
int refers tonp.int_ ,bool meansnp.bool_ , thatfloat isnp.float_ andcomplex isnp.complex_ . The other data-types do not have Python equivalents.
还有-
float_ - Shorthand for float64.
这就是为什么即使您使用
根据另一个问题的要求,最好的解决方案是将每个标量值设为-后转换为普通浮点对象-
1 | float(new_array[0]) |
我能想到的解决方案是为
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) |
您可以像这样创建匿名类型
1 2 3 | >>> new_array = my_array.astype(type('float', (float,), {})) >>> type(new_array[0]) <type 'float'> |
如果您试图停留在numpy中,这不是一个好主意,但是如果您已完成计算并移入本机python,则可以使用
1 | ndarray.tolist() |
这会将数组转换为适当的本机类型的列表。它也适用于numpy标量值。