问题
I'm trying to convert a numpy.uint64 (which is outputted by numpy.sum()) to a decimal without losing precision with the Decimal module.
>>> from decimal import Decimal
>>> import numpy as np
>>>
>>> sum = np.sum(1000000000000000000)
>>> type(sum)
<type 'numpy.int64'>
>>> Decimal(sum)
Decimal('1000000000000000000')
>>>
>>> sum = np.sum(1000000000000000000000)
>>> type(sum)
<type 'long'>
>>> Decimal(sum)
Decimal('1000000000000000000000')
>>>
>>> sum = np.sum(10000000000000000000)
>>> type(sum)
<type 'numpy.uint64'>
>>> Decimal(sum)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert 10000000000000000000 to Decimal
回答1:
decimal.Decimal
doesn't understand NumPy inputs, so convert the numpy.uint64
to a Python scalar with the item method before calling decimal.Decimal
:
Decimal(np.sum(whatever).item())
回答2:
In my case, just upgraded from pandas 0.20.3 to 0.21 fixed it
来源:https://stackoverflow.com/questions/43214243/python-decimal-module-doesnt-work-on-uint64