如何将numpy
{'float64'
转换为类型'float'
?具体来说,我如何用dtype
{array
转换成dtype
{
考虑一下:
>>> 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及其答案。
您可以创建一个匿名类型
float
,如下所示是的,实际上当您使用Python的本机
float
指定数组的数据类型时,numpy会将其转换为float64
。如documentation -所示以及-
这就是为什么即使使用
float
将整个数组转换为float,它仍然使用np.float64
。根据另一个问题的要求,最好的解决方案是将每个标量值取为-
我可以想到的一个解决方案是为
float
创建一个子类并将其用于强制转换(尽管对我来说这看起来很糟糕)。但如果可能的话,我更喜欢前面的解决方案。示例-相关问题 更多 >
编程相关推荐