python dataframe/series 的正确舍入
python correct rounding for dataframe/series
在 OP 记下我的问题之前,请注意我已经查看了以下帖子:
round() doesn't seem to be rounding properly
他们没有回答我的问题。
我的问题与此类似,因为您可能已经知道 python 没有正确舍入一半值(以标准方式),即:
2.5 -> 2
2.25 -> 2.2
而我们知道:
2.5 应该是 ->3
2.25 应该是 -> 2.3 等等...
现在我有一个 Pandas 系列 object 在下面说:
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 object?
非常感谢您的帮助
我意识到我把它弄得比看起来更复杂,我只是做了一个小技巧,我所要做的就是在数字中加上 0.00000001 say 并且可以用正常的方式进行舍入.
round(2.25+0.000001, 1) -> 2.3
在 OP 记下我的问题之前,请注意我已经查看了以下帖子:
round() doesn't seem to be rounding properly
他们没有回答我的问题。
我的问题与此类似,因为您可能已经知道 python 没有正确舍入一半值(以标准方式),即:
2.5 -> 2
2.25 -> 2.2
而我们知道:
2.5 应该是 ->3
2.25 应该是 -> 2.3 等等...
现在我有一个 Pandas 系列 object 在下面说:
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 object?
非常感谢您的帮助
我意识到我把它弄得比看起来更复杂,我只是做了一个小技巧,我所要做的就是在数字中加上 0.00000001 say 并且可以用正常的方式进行舍入.
round(2.25+0.000001, 1) -> 2.3