为什么此数组没有属性'log10'? [英] Why does this array has no attribute 'log10'?

查看:88
本文介绍了为什么此数组没有属性'log10'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算ndarray的log10,但是出现以下错误:AttributeError:"float"对象没有属性"log10",通过做一些研究,我发现它与python处理数字值的方式,但我仍然不明白为什么会收到此错误.

I'm trying to calculate the log10 of an ndarray, but I'm getting the following error: AttributeError: 'float' object has no attribute 'log10', by doing some research I found that it has to do with the way python handles numeric values, but I still can't get why I'm getting this error.

>>> hx[0:5,:]
array([[0.0],
       [0.0],
       [0.0],
       [0.0],
       [0.0]], dtype=object)
>>> type(hx)
<class 'numpy.ndarray'>
>>> type(hx[0,0])
<class 'float'>
>>> test
array([[ 0.],
       [ 0.],
       [ 0.]])
>>> type(test)
<class 'numpy.ndarray'>
>>> type(test[0,0])
<class 'numpy.float64'>
>>> np.log10(test)
array([[-inf],
       [-inf],
       [-inf]])
>>> np.log10(hx[0:5,:])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'log10'
>>> np.log10(np.float64(0))
-inf
>>> np.log10([np.float64(0)])
array([-inf])
>>> np.log10([[np.float64(0)]])
array([[-inf]])
>>> np.log10(float(0))
-inf
>>> np.log10([[float(0)]])
array([[-inf]])

我认为原因是type(hx [0,0])是Python浮点类,但我也能够计算出浮点类的log10.我很确定我应该强制转换某种值,以便可以将其作为numpy.log10()的参数来处理,但我找不到它.

I thought the reason was that type(hx[0,0]) is a Python float class, but I was able to calculate the log10 of a float class as well. I'm pretty sure I'm supposed to cast some kind of value so it can be handled as a parameter for numpy.log10(), but I can't spot it.

推荐答案

hx的数据类型为object.您可以在输出中看到它,并且可以检查hx.dtype.数组中存储的对象显然是Python浮点数. Numpy不知道您可能在对象数组中存储了什么,因此它尝试将其函数(例如log10)分派到数组中的对象.之所以失败,是因为Python浮点数没有log10方法.

The data type of hx is object. You can see that in the output, and you can check hx.dtype. The objects stored in the array are apparently Python floats. Numpy doesn't know what you might have stored in a object array, so it attempts to dispatch its functions (such as log10) to the objects in the array. This fails because Python floats don't have a log10 method.

在代码开头尝试以下操作:

Try this at the beginning of your code:

hx = hx.astype(np.float64)

这篇关于为什么此数组没有属性'log10'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆