如何将numpy.int32转换为十进制。十进制

开发者爱玛

我正在使用在函数调用中使用一些十进制类型的args的库。但是我有numpy.int32类型变量。将其传递给函数调用时,出现以下错误:

TypeError:不支持从numpy.float32转换为Decimal

这意味着库尝试将我传递的参数转换为decimal.Decimal,但失败。请让我知道,在传递给库之前如何转换变量。谢谢

消毒用户

十进制接受本机Python类型。

numpyType.item() 返回相应的本机类型。

这是一个例子:

import decimal
import numpy as np

# other library function
# will raise exception if passed argument is not Decimal
def library(decimal_arg):
    if type(decimal_arg) is not decimal.Decimal:
        raise TypeError('Not a decimal.Decimal')
    return decimal_arg

# wrapper with try block
def try_library(arg):
    try:
        print(library(arg))
    except TypeError as e:
        print(e)

def main():
    # we have some numpy types
    a = np.float32(1.1)
    b = np.int32(2)
    c = np.uint64(3000)

    # passing the numpy type does not work
    try_library(a)

    # Decimal's constructor doesn't know conversion from numpy types
    try:
        try_library(decimal.Decimal(a))
    except TypeError as e:
        print(e)

    # calling a.item() will return native Python type
    # constructor of Decimal accepts a native type
    # so it will work
    try_library(decimal.Decimal(a.item()))
    try_library(decimal.Decimal(b.item()))
    try_library(decimal.Decimal(c.item()))

main()
# output:

# Not a decimal.Decimal
# Cannot convert 1.1 to Decimal
# 1.10000002384185791015625
# 2
# 3000

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章