【发布时间】:2018-08-10 20:07:16
【问题描述】:
我正在使用的系列:
import pandas as pd
from decimal import Decimal, BasicContext
df = pd.Series([14978.22,
16025.429160000002,
209.97803999999996,
618.20369,
605.607,
1431.0916,
30.53575,
23.77272,
404.79368999999997,
55580.152319999994
])
df2 = df.apply(str).apply(Decimal, context=BasicContext)
我想使用“ROUND_HALF_UP”(这是用于 BasicContext 的四舍五入)将 df 中的所有值四舍五入到 5 位。所以,我这样做:
df2.apply(round, ndigits=5)
但是,这会引发错误:
Traceback(最近一次调用最后一次):
文件“”,第 1 行,在 df2.apply(round, ndigits=5)
文件 "C:\Users\Guest\AppData\Roaming\Python\Python36\site-packages\pandas\core\series.py", 第 3194 行,申请中 mapped = lib.map_infer(values, f, convert=convert_dtype)
文件“pandas/_libs/src\inference.pyx”,第 1472 行,在 pandas._libs.lib.map_infer
文件 "C:\Users\Guest\AppData\Roaming\Python\Python36\site-packages\pandas\core\series.py", 第 3181 行,在 f = lambda x: func(x, *args, **kwds)
InvalidOperation:类'decimal.InvalidOperation'
但是,四舍五入有效:
df2.apply(round, ndigits=4)
为什么会发生这种情况,我该如何解决?
【问题讨论】:
-
round应用于Decimal对象要求当前的 Decimal 上下文具有足够的精度来表示结果。您使用的BasicContext的精度为 9,但16025.429160000002在该点后四舍五入到 5 位需要 10 位有效数字来表示。
标签: python pandas floating-point decimal rounding