Pandas Dataframe:我想在划分列时使用 round(),但出现错误

lif*_*ner 1 dataframe python-3.x pandas

TypeError: ufunc 循环不支持 float 类型的参数 0,该参数没有可调用的 rint 方法

state_trend['Percent Change'].round(2)

该列中有一堆浮点数和整数。知道问题是什么吗?

dmo*_*ner 5

错误消息在这里有点误导,实际上与零无关。

快速回答是:

state_trend['Percent Change'].astype(float).round(2)
Run Code Online (Sandbox Code Playgroud)

当该系列的类型为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
Run Code Online (Sandbox Code Playgroud)

但是当您将系列转换为对象时,您会收到舍入错误:

>>> 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

Run Code Online (Sandbox Code Playgroud)

这是有和没有零的情况:

>>> 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
Run Code Online (Sandbox Code Playgroud)

所以我只是在四舍五入之前转换为浮点数:

>>> t1.astype(float).round(2)
0    0.00
1    0.50
2    0.67
dtype: float64
>>> 
Run Code Online (Sandbox Code Playgroud)

state_trend['Percent Change']最后一个问题是类型是如何变成的object......通常,如果您之前没有值或第一个系列生成类型对象本身的百分比,则会发生这种情况。