Monday 19 December 2016

python - decimal.InvalidOperation error when rounding values in Series

Series I'm working with:



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)



I'd like to round all the values in df to 5 digits using "ROUND_HALF_UP" (which is the rounding used for BasicContext). So, I do this:



df2.apply(round, ndigits=5)


However, this throws an error:





Traceback (most recent call last):



File "", line 1, in
df2.apply(round, ndigits=5)



File
"C:\Users\Guest\AppData\Roaming\Python\Python36\site-packages\pandas\core\series.py",
line 3194, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)




File "pandas/_libs/src\inference.pyx", line 1472, in
pandas._libs.lib.map_infer



File
"C:\Users\Guest\AppData\Roaming\Python\Python36\site-packages\pandas\core\series.py",
line 3181, in
f = lambda x: func(x, *args, **kwds)



InvalidOperation: class 'decimal.InvalidOperation'





However, rounding to 4 digits works:



df2.apply(round, ndigits=4)


Why is this happening and how do I work around this?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...