python - 如何将 numpy.int32 转换为 decimal.Decimal

标签 python numpy

我正在使用一个在函数调用中使用一些十进制类型参数的库。但是我有 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/

相关文章:

python - 使用python从csv文件中删除特殊字符

python - pandas 从数组中获取嵌套的字符串值

python - 带和不带笔记本的 IPython 差异

python - 检查 python 列表/numpy ndarray 中是否存在重复项的最快方法

python 到 arduino 串口读写

javascript - 将 CKeditor 集成到 Flask 时 CSRF 验证失败

python - 在 Python 中的 scipy/numpy 中计算 2D 矩阵的 z 分数

python - 类型错误 : only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

python - 如何在方法中传递实例的引用?

python - pandas to_numeric/to_* 如果输入是数据帧切片则引发缓冲区错误