【问题标题】:AttributeError: 'numpy.float64' object has no attribute 'log10'AttributeError:“numpy.float64”对象没有属性“log10”
【发布时间】:2017-11-09 17:51:32
【问题描述】:

我正在尝试使用 sklearn.LinearRegression 找到大量短系列的对数斜率。数据是从 pandas 数据框的行中提取的,如下所示:

bp01    1.12
bp02    1.12
bp03    1.08
bp04    0.99
bp05    1.08
bp06    1.19
bp07    1.17
bp08    1.05
bp09     0.8
bp10    0.96
bp11    0.97
bp12    1.12
bp13    0.91
bp14    0.96
bp15    1.05
bp16    0.93
bp17    0.97
bp18    0.92
bp19    0.89
bp20       0
Name: 42029, dtype: object

但是,当我尝试使用 np.log10 时,在系列中我收到以下错误:

In[27]: test.apply(np.log10)
Traceback (most recent call last):

  File "<ipython-input-27-bccff3ed525b>", line 1, in <module>
    test.apply(np.log10)

  File "C:\location", line 2348, in apply
    return f(self)

AttributeError: 'numpy.float64' object has no attribute 'log10'

我不确定为什么会出现此错误,np.log10 应该与我所看到的 numpy.float64 一起使用。想法?

【问题讨论】:

  • 试试这个:test.apply(lambda x: np.log10(x))
  • test 是一个 pd.series。 apply 应该将系列中的每个值都传递给 np.log10 命令,对吗?
  • 查看this question是否重复。
  • 你调用了一个浮点变量np

标签: python numpy


【解决方案1】:

numpy.log10 是一个“ufunc”,Series.apply(func) 方法对 numpy ufunc 进行了特殊测试,这使得 test.apply(log10) 等同于 np.log10(test)。这意味着test,一个Pandas Series 实例,被传递给log10test的数据类型是object,也就是说test中的元素可以是任意的Python对象。 np.log10 不知道如何处理这样的对象集合(它不“知道”这些对象实际上都是 np.float64 实例),因此它尝试将计算分派给Series。为此,它希望元素本身具有log10 方法。这就是错误发生的时候:Series(在本例中为np.float64 实例)中的元素没有log10 方法。

np.log10(test.astype(np.float64))test.astype(np.float64).apply(np.log10) 是两个可以满足您需求的替代表达式。本质部分是test.astype(np.float64)Series对象的数据类型从object转换为np.float64

【讨论】:

    【解决方案2】:

    在使用标准偏差 (np.std) 而不是 np.log10 时,我收到了类似的错误消息:

    'AttributeError:'numpy.float64'对象没有属性'sqrt',

    虽然我之前已经通过np.asarray(X) 将 Pandas 对象 X 转换为 numpy 数组。

    我可以通过应用上述解决方案来解决这个问题:

    X = pd.read_excel('file.xls')
    Y = np.asarray(X).astype(np.float64)
    Z = np.std(Y,axis=0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-17
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2020-03-20
      • 2017-06-09
      • 2012-12-01
      相关资源
      最近更新 更多