python-3.x - Pandas Dataframe:我想在划分列时使用 round(),但出现错误
问题描述
TypeError:ufunc 的循环不支持浮点类型的参数 0,它没有可调用的 rint 方法
state_trend['Percent Change'].round(2)
该列中有一堆浮点数和整数。知道问题是什么吗?
解决方案
错误消息在这里有点误导,实际上与零无关。
快速的答案是:
state_trend['Percent Change'].astype(float).round(2)
当系列是object类型时,我设法复制了错误。对于浮点格式,round 函数运行良好。在对象格式的情况下,你会得到同样的错误,有或没有零
所以所有这些代码都按预期工作:
import pandas as pd
>>> s1 = pd.Series([0, 1, 2]) / pd.Series([1,2,3])
>>> s2 = pd.Series([1, 1, 2]) / pd.Series([1,2,3])
>>> s1.round(2)
0 0.00
1 0.50
2 0.67
dtype: float64
>>> s2.round(2)
0 1.00
1 0.50
2 0.67
dtype: float64
但是,当您将系列转换为对象时,您会得到舍入错误:
>>> t1 = s1.astype(object)
>>> t2 = s2.astype(object)
>>> t1.round(2)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/pandas/core/series.py", line 2218, in round
result = self._values.round(decimals)
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
这是有和没有零的:
>>> t2.round(2)
AttributeError: 'float' object has no attribute 'rint'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/pandas/core/series.py", line 2218, in round
result = self._values.round(decimals)
TypeError: loop of ufunc does not support argument 0 of type float which has no callable rint method
所以我只是在四舍五入之前转换为浮点数:
>>> t1.astype(float).round(2)
0 0.00
1 0.50
2 0.67
dtype: float64
>>>
最后一个问题是 type 是如何state_trend['Percent Change']
变成的object
……通常,如果您之前有 None 值或第一个系列生成了 type 对象本身的百分比 where ,则会发生这种情况。
推荐阅读
- java - 使点可拖动并存储新坐标 JavaFx
- visual-studio-code - 如何在 launch.json 中将 vscode 实时服务器作为任务启动
- gupshup - gupshup api中特定号码的选择加入状态
- ansible - 在 ansible 2.3 版中导入或包含剧本
- php - woocommerce 产品属性为空
- javascript - 如何防止浏览器在基于脚本的 Web 应用程序的 URL 中添加用户参数?
- android - SQLite UPDATE WHERE 性能
- javascript - 将数组传递给按钮的 href
- discord - Discord Python 重写 - Reaction 帮助 (Cog)
- python - Python Scrapy - 如何在不忽略过滤器的情况下获取这些名称?