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

查看:176
本文介绍了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天全站免登陆