Python Decimal模块不适用于uint64

时间:2017-04-04 17:50:30

标签: python numpy decimal

我试图将numpy.uint64(由numpy.sum()输出)转换为小数而不会丢失Decimal模块的精度。

>>> 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

2 个答案:

答案 0 :(得分:2)

decimal.Decimal不了解NumPy输入,因此在调用numpy.uint64之前将decimal.Decimal转换为item method的Python标量:

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

答案 1 :(得分:0)

在我的情况下,刚刚从pandas 0.20.3升级到0.21修复了它