• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python/Numpy AttributeError:'float' 对象没有属性 'sin'

用户头像
it1352
帮助1

问题说明

我要把这个贴在这里是因为它太像栗子了,让我有些头疼.这可以说是四年前发布的这个问题的副本,但是如果有人遇到我在这里遇到的特定的 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...

正确答案

#1

失败的原因与:

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!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfgiib
系列文章
更多 icon
同类精品
更多 icon
继续加载