我正在使用一个在函数调用中使用一些十进制类型参数的库。但是我有 numpy.int32 类型变量。当我将它传递给函数调用时,出现以下错误:
TypeError: conversion from numpy.float32 to Decimal is not supported
这意味着库尝试将我传递的参数转换为 decimal.Decimal 但失败了。请让我知道,在传递给库之前如何转换我的变量。 谢谢
最佳答案
Decimal 接受 native 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
关于python - 如何将 numpy.int32 转换为 decimal.Decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61361910/