如何确定一个数字是否是任何类型的 int (core 或 numpy,有符号或无符号) ?

我需要测试一个变量是 int类型的,还是 np.int*np.uint*类型的,最好使用单一条件(i.e.or)。

经过一些测试,我想:

  • isinstance(n, int)将只匹配 intnp.int32(或 np.int64取决于平台) ,
  • np.issubdtype(type(n), int)似乎匹配所有 intnp.int*,但不匹配 np.uint*

这就引出了两个问题: np.issubdtype会匹配 任何类型的有符号整数吗?可以在单个检查中确定一个数字是任何类型的有符号整型还是无符号整型?

这是关于 整数的测试,测试应该返回类似于 float 的 False

48512 次浏览

我建议将类型元组传递给 pythonisinstance()内置函数。关于 np.issubtype()的问题,它不匹配任何类型的有符号整型,它决定一个类是否是第二个类的子类。由于所有的整数类型(int8、 int32等)都是 int的子类,所以如果将这些类型中的任何一个与 int一起传递,它将返回 True。

这里有一个例子:

>>> a = np.array([100])
>>>
>>> np.issubdtype(type(a[0]), int)
True
>>> isinstance(a[0], (int, np.uint))
True
>>> b = np.array([100], dtype=uint64)
>>>
>>> isinstance(b[0], (int, np.uint))
True

另外,作为一种更通用的方法(当您只想匹配某些特定类型时是不合适的) ,您可以使用 np.isreal():

>>> np.isreal(a[0])
True
>>> np.isreal(b[0])
True
>>> np.isreal(2.4) # This might not be the result you want
True
>>> np.isreal(2.4j)
False

NumPy 提供了可以/应该用于子类型检查的基类,而不是 Python 类型。

使用 np.integer检查有符号或无符号整数的任何实例。

使用 np.signedintegernp.unsignedinteger检查有符号类型或无符号类型。

>>> np.issubdtype(np.uint32, np.integer)
True
>>> np.issubdtype(np.uint32, np.signedinteger)
False
>>> np.issubdtype(int, np.integer)
True
>>> np.issubdtype(np.array([1, 2, 3]).dtype, np.integer)
True

所有浮点数或复数类型在测试时将返回 False

np.issubdtype(np.uint*, int)始终是 False,因为 Pythonint是有符号类型。

在文档 here中可以找到一个有用的参考,它显示了所有这些基类之间的关系。

enter image description here

基于@Alex Riley 的树型答案,我设法通过将我的值映射到这个 fn 来解决同样的问题。希望对某些人有用。

def convert_to_native_type(value):
if isinstance(value, np.integer):
return int(value)
elif isinstance(value, np.float):
return float(value)
else:
return value