Python/Numpy AttributeError:'float' 对象没有属性 'sin' [英] Python / Numpy AttributeError: 'float' object has no attribute 'sin'

查看:53
本文介绍了Python/Numpy AttributeError:'float' 对象没有属性 'sin'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要把这个贴在这里是因为它太像栗子了,让我有些头疼.这可以说是四年前发布的这个问题的副本,但是如果有人遇到我在这里遇到的特定的 pandas-numpy 不兼容问题,我会再次发布它.或者也许有人会想出更好的答案.

I'm going to post this here because it's quite a chestnut and caused me some head-scratching. It's arguably a duplicate of this question posted four years ago but I'll post it again in case someone has the specific pandas-numpy incompatibility that I have encountered here. Or maybe someone will come up with a better answer.

代码片段:

#import pdb; pdb.set_trace()

# TODO: This raises AttributeError: 'float' object has no attribute 'sin'
xr = xw + L*np.sin(θr)

输出:

Traceback (most recent call last):
  File "MIP_MPC_demo.py", line 561, in <module>
    main()
  File "MIP_MPC_demo.py", line 557, in main
    animation = create_animation(model, data_recorder)
  File "MIP_MPC_demo.py", line 358, in create_animation
    xr = xw + L*np.sin(θr)
AttributeError: 'float' object has no attribute 'sin'

到目前为止我尝试过的:

What I've tried so far:

(Pdb) type(np)
<class 'module'>
(Pdb) np.sin
<ufunc 'sin'>
(Pdb) type(θr)
<class 'pandas.core.series.Series'>
(Pdb) np.sin(θr.values)
*** AttributeError: 'float' object has no attribute 'sin'
(Pdb) θr.dtype
dtype('O')
(Pdb) np.sin(θr)
*** AttributeError: 'float' object has no attribute 'sin'
(Pdb) θr.sin()
*** AttributeError: 'Series' object has no attribute 'sin'
(Pdb) θr.values.sin()
*** AttributeError: 'numpy.ndarray' object has no attribute 'sin'
(Pdb) θr.values.max()
nan
(Pdb) np.max(θr)
0.02343020407511865
(Pdb) np.sin(θr)
*** AttributeError: 'float' object has no attribute 'sin'
(Pdb) np.sin(θr[0])
0.0

顺便说一句,这个例外至少可以说是误导.另一个人发布这个问题已经四年了.有没有其他人同意应该修改这点以及有关如何修改的任何建议?异常的解释是什么?numpy 是否在做某种映射操作,并试图调用 θr 的每个元素的 sin 方法?

On a side-note, the exception is misleading to say the least. It's been four years since the other person posted the issue. Does anyone else agree that this should be modified and any suggestions on how? What is the explanation for the exception? Is numpy doing some kind of map operation and trying to call the sin method of each element of θr?

我会尽快发布答案...

I will post the answer shortly...

推荐答案

失败的原因与:

import numpy as np
arr = np.array([1.0, 2.0, 3.0], dtype=object)
np.sin(arr)
# AttributeError: 'float' object has no attribute 'sin'

当在对象数组上调用np.sin时,它会尝试调用每个元素的sin方法.

When np.sin is called on an object array, it tries to call the sin method of each element.

如果你知道 θr.values 的 dtype,你可以用以下方法解决这个问题:

If you know the dtype of θr.values, you can fix this with:

arr = np.array(θr.values).astype(np.float64)  # assuming the type is float64
np.sin(arr)  # ok!

这篇关于Python/Numpy AttributeError:'float' 对象没有属性 'sin'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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