简体   繁体   中英

Python Decimal module doesn't work on uint64

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

decimal.Decimal无法理解NumPy输入,因此请在调用decimal.Decimal之前,使用item方法numpy.uint64转换为Python标量:

Decimal(np.sum(whatever).item())

就我而言,刚刚从熊猫0.20.3升级到0.21修复了它

您还可以在转换为十进制之前将其转换为浮点数:

Decimal(float(sum))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM