Bil*_*ill 5 python floating-point numpy attributeerror pandas
我要把这个贴在这里,因为它是一个栗子,让我有些头疼。这可以说是四年前发布的这个问题的副本,但我会再次发布,以防有人遇到我在这里遇到的特定 pandas-numpy 不兼容问题。或者也许有人会想出更好的答案。
代码片段:
#import pdb; pdb.set_trace()
# TODO: This raises AttributeError: 'float' object has no attribute 'sin'
xr = xw + L*np.sin(?r)
Run Code Online (Sandbox Code Playgroud)
输出:
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'
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试过的:
(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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,例外至少可以说是误导。另一个人发布这个问题已经四年了。有没有其他人同意应该修改这点以及有关如何修改的任何建议?异常的解释是什么?numpy 是否在执行某种映射操作并尝试调用 的sin每个元素的方法?r?
我会尽快发布答案...
失败的原因与以下相同:
\n\nimport numpy as np\narr = np.array([1.0, 2.0, 3.0], dtype=object)\nnp.sin(arr)\n# AttributeError: 'float' object has no attribute 'sin'\nRun Code Online (Sandbox Code Playgroud)\n\n当np.sin对对象数组调用时,它会尝试调用sin每个元素的方法。
如果您知道 的 dtype \xce\xb8r.values,则可以使用以下方法修复此问题:
arr = np.array(\xce\xb8r.values).astype(np.float64) # assuming the type is float64\nnp.sin(arr) # ok!\nRun Code Online (Sandbox Code Playgroud)\n