【发布时间】:2021-06-03 16:10:24
【问题描述】:
在 OP 取消我的问题之前,请注意我已经查看了以下帖子: pandas python - round() not behaving correctly
round() doesn't seem to be rounding properly
他们没有回答我的问题。
我的问题与那些类似,因为您可能已经知道 python 不能正确地舍入一半值(以标准方式),即:
2.5 -> 2
2.25 -> 2.2
而我们知道:
2.5 应该是 ->3
2.25 应该是 -> 2.3 等等...
现在我有一个 Pandas 系列对象,如下所示:
| index | Another header |
|---|---|
| 1 | 2.25 |
| 2 | 3.55 |
| 3 | 4.44 |
| 4 | 5.56 |
| 5 | 6.23 |
| 6 | 7.45 |
我目前有代码Series.apply(lambda x: round(x, 1))
并创建了这个函数:
def correctRound(x: float, n: int):
target_precision = "1." + "0" * n
rounded_x = float(Decimal(x).quantize(Decimal(target_precision), dwRound))
if n == 0:
rounded_x = int(rounded_x)
return rounded_x
然而这不能在 Series 上工作,我怎样才能正确地舍入 DataFrame 或 Series 对象?
非常感谢您的帮助
【问题讨论】:
-
python 没有正确舍入一半的值, -- 此语句不正确。您显然相信只有一种可接受的舍入方法。那是错误的。 Python 实现了“银行家四舍五入”,将 x.5 舍入到最接近的偶数。 2.25 变成 2.2,但 2.35 变成 2.4。这是完全正确的,即使它不是您想要的舍入。
标签: python pandas dataframe rounding series