【问题标题】:AttributeError: 'numpy.float64' object has no attribute 'to_numpy'AttributeError:“numpy.float64”对象没有属性“to_numpy”
【发布时间】:2020-04-26 04:12:49
【问题描述】:

我是 Python 的新手,我不明白为什么会出现这个错误。 这是我写的代码:

var_1 = pd.DataFrame({'Vcond':[], 'Rsquared':[]})

for j in clim :
    varj = Cmean.loc[j][j]
    varz = Cmean.loc['Zi']['Zi']
    covzj = Cmean.loc['Zi'][j]
    B = np.linalg.inv(varj.to_numpy())
    Vcondj = varz-covzj @ B @ covzj
    Rsquared = (varz - Vcondj)/varz 
    var_1.loc[j]={'Vcond': Vcondj, 'Rsquared': Rsquared}

print(var_1)

还有错误:

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

我的老师说要使用 .to_numpy() 这种方式来计算矩阵的逆,但它似乎不起作用。任何帮助将不胜感激!

【问题讨论】:

  • 嗨。确保在此处提问时定义您在代码 sn-p 中使用的所有名称。例如,Cmean 是什么?更多详情见mcve
  • 您好,感谢您的建议。我想定义所有变量,但 Cmean 是一个 DataFrame,它是通过大量操作创建的。不知道怎么把最终的数据帧写成代码短...
  • 在 Python 中,每个对象(变量)都属于一个特定的类,有自己的 methodsto_numpypandas.DataFrame(和 Series)的方法。 varj 不是其中之一,也没有那种方法。作为初学者,你会经常遇到这样的 AttributeError 。试着理解变量实际上是什么,应该是什么。您还应该学习查找语言和模块参考。

标签: python numpy matrix


【解决方案1】:

对于我从另一个问题中剩余的 df 数据框:

In [907]: type(df)                                                                                     
Out[907]: pandas.core.frame.DataFrame
In [908]: type(df.loc[1])                                                                              
Out[908]: pandas.core.series.Series
In [909]: type(df.loc[1][1])                                                                           
Out[909]: numpy.int64

查看连续的loc 索引步骤如何给出Series,然后给出数值。

dataframe 的to_numpy 方法产生一个二维数组:

In [912]: df.to_numpy().shape                                                                          
Out[912]: (22, 2)

应用于Series,我们得到一个一维数组:

In [913]: df.loc[1].to_numpy()                                                                         
Out[913]: array([28, 13])

但正如您的错误所示,就是这样。 np.floatobject does not have ato_numpymethod. It already is anumpy` 对象。

在编写这样的代码时,您应该知道每一步会产生什么样的对象。并准备好测试这些知识。错误的猜测会产生错误。

【讨论】:

  • 谢谢你的解释,我记住了。
【解决方案2】:

varj 似乎是numpy.float64 类型,因此您无法再将其转换为 numpy 数据类型。由于您提到要使用 to_numpy 来反转矩阵,因此您可能希望将其应用于您的数据框。

【讨论】:

  • 谢谢!问题是 varj 正如你所说的那样是一个 numpy.float64 类型,我必须使用 .to_numpy 进行下一次计算,其中包含 2 个变量。在这个例子中,它只有一个变量......这太荒谬了。
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 2019-07-06
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2012-12-01
  • 2021-04-19
相关资源
最近更新 更多