Python Decimal module doesn't work on uint64

妖精的绣舞 提交于 2020-02-25 02:07:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!