gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:39:40 26 4
gpt4 key购买 nike

如何将 numpy array 从类型 'float64' 转换为类型 'float'?具体来说,我如何将 an entire arraydtype '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及其答案。

最佳答案

是的,实际上当您使用 Python 的原生 float 指定数组的 dtype 时,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 对象

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)

关于python - 如何将 numpy 数组从 'float64' 转换为 'float',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com