【问题标题】:Why does this array has no attribute 'log10'?为什么这个数组没有属性'log10'?
【发布时间】:2017-10-28 22:18:10
【问题描述】:

我正在尝试计算 ndarray 的 log10,但我收到以下错误:AttributeError: 'float' object has no attribute 'log10',通过做一些研究我发现它与python 处理数值的方式,但我仍然不明白为什么会出现此错误。

>>> 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() 的参数处理,但我无法发现它。

【问题讨论】:

  • 你是如何创建hx的?

标签: python numpy multidimensional-array


【解决方案1】:

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

在代码的开头试试这个:

hx = hx.astype(np.float64)

【讨论】:

  • 如果错误是由numpy中的调用触发的,为什么回溯中没有给出该代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
相关资源
最近更新 更多