为什么Pandas四舍五入法不四舍五入到一?

2024-10-01 22:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我贴这个我认为是答案,因为我在这里找不到类似的问题答案。在

我希望pandasround方法将0.5舍入到1。在

>>> import pandas as pd
>>> pd.Series([0.5, 1.5, 2.5, 3.5, 4.5]).round()
0    0.0
1    2.0
2    2.0
3    4.0
4    4.0
dtype: float64

更奇怪的是:Python的round方法在Python 2.7和3.6中有不同的行为:

Python 2.7:

^{pr2}$

Python 3.6:

>>> [round(x) for x in [0.5, 1.5, 2.5, 3.5, 4.5]]
[0, 2, 2, 4, 4]

这与浮点表示或我的平台(macosx)有关吗?在


Tags: 方法答案inimportpandasforasseries
2条回答

这确实是由于floating point arithmetic,如Python 3documentation for ^{}中所述,其中指出:

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.

我相信这实际上是python中预期的行为,而不是浮点问题。看看documentation

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)

相关问题 更多 >

    热门问题