【问题标题】:python correct rounding for dataframe/series数据框/系列的python正确舍入
【发布时间】: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


【解决方案1】:

我意识到我让这比看起来更复杂,我只是做了一个小技巧,我所要做的就是在数字中添加 0.00000001 说,然后可以按正常方式进行四舍五入。

round(2.25+0.000001, 1) -> 2.3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多