pandas 取整系列时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41015906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:35:11  来源:igfitidea点击:

Getting an error when rounding a series

pythonpandasrounding

提问by Mauro Gentile

I have a series of floats. It is the results of a data frame sum() operation. I need to round all its elements to integer but I get an error:

我有一系列的花车。它是数据帧 sum() 操作的结果。我需要将其所有元素四舍五入为整数,但出现错误:

[in]:
A= mins.sum().iloc[1:]/60 
# this line works fine. The .iloc is to get rid of a text column.

[in]:
print(A)

[out]:
Min bad                     249.5
Min pr-ul                   967.57
intra com diff              178.05
Intra com diff 60           184.27
dtype: object

Now, if I try to round I get an error:

现在,如果我尝试四舍五入,我会收到一个错误:

[in]:
A.round()

[out]:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-528-685b5302b717> in <module>()
  3 
  4 print(A)
  ----> 5 A.round()

 //anaconda/lib/python3.5/site-packages/pandas/core/series.py in round(self,decimals, *args, **kwargs)
   1303         """
   1304         nv.validate_round(args, kwargs)
   -> 1305         result = _values_from_object(self).round(decimals)
   1306         result = self._constructor(result, index=self.index).__finalize__(self)
   1307 

   AttributeError: 'float' object has no attribute 'rint'

Can anyone tell me why is that and ho I can fix it? I guess that the root of the problem is because the Series is "object" type. But what is this? It only contains float numbers!!! it is the results of a data frame summarization

谁能告诉我为什么会这样,我可以解决它吗?我想问题的根源是因为系列是“对象”类型。但这是什么?它只包含浮点数!!!它是数据框汇总的结果

thank you in advance for helping

提前感谢您的帮助

回答by Jonathan Biemond

Cast the series to type float using .astype(float)as suggested by Mark Dickinson. In your case you should use A.astype(float).round()

.astype(float)按照 Mark Dickinson 的建议,将系列转换为使用 float 类型。在你的情况下,你应该使用A.astype(float).round()

I ran into the same error rounding a column in a data frame, casting to a float solved it for me. Thanks to Mark Dickinson.

我在对数据框中的列进行四舍五入时遇到了同样的错误,转换为浮点数为我解决了这个问题。感谢马克·狄金森。