【问题标题】:decimal.InvalidOperation error when rounding values in Series舍入Series中的值时出现decimal.InvalidOperation错误
【发布时间】: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


【解决方案1】:

您是否尝试过捕获decimal.InvalidOperation 异常?你应该有一个tryexcept

try:
    # your code 
except DecimalException as e:
    print(e)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多