在 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 Series 对象,如下所示:
索引 | 另一个标题 |
---|---|
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 对象?
非常感谢您的帮助
答案 0 :(得分:0)
我意识到这比看起来更复杂,我只是做了一个小技巧,我所要做的就是在数字中添加 0.00000001 say 并且四舍五入可以以正常方式完成。< /p>
round(2.25+0.000001, 1) -> 2.3