37

如何检查 numpy dtype 是否是整数?我试过:

issubclass(np.int64, numbers.Integral)

但它给了False


更新:它现在给出True.

4

6 回答 6

64

Numpy 具有类似于类层次结构的 dtype 层次结构(标量类型实际上具有反映 dtype 层次结构的真正类层次结构)。您可以使用np.issubdtype(some_dtype, np.integer)来测试 dtype 是否是整数 dtype。请注意,与大多数使用 dtype 的函数一样,np.issubdtype()会将其参数转换为 dtype,因此可以使用任何可以通过np.dtype()构造函数创建 dtype 的东西。

http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#specifying-and-constructing-data-types

>>> import numpy as np
>>> np.issubdtype(np.int32, np.integer)
True
>>> np.issubdtype(np.float32, np.integer)
False
>>> np.issubdtype(np.complex64, np.integer)
False
>>> np.issubdtype(np.uint8, np.integer)
True
>>> np.issubdtype(np.bool, np.integer)
False
>>> np.issubdtype(np.void, np.integer)
False

在 numpy 的未来版本中,我们将确保标量类型已注册到适当的numbersABC。

于 2014-03-18T10:16:45.893 回答
18

请注意,这np.int64不是 dtype,它是 Python 类型。如果您有一个实际的 dtype(通过dtype数组的字段访问),您可以使用np.typecodes您发现的 dict:

my_array.dtype.char in np.typecodes['AllInteger']

如果你只有一个类型如np.int64,你可以先获取一个类型对应的dtype,然后如上查询:

>>> np.dtype(np.int64).char in np.typecodes['AllInteger']
True
于 2014-03-18T07:17:58.560 回答
7

基于以前的答案和评论,我决定使用Python 的内置方法和模块type的对象属性:dtypeissubclass()numbers

import numbers
import numpy

assert issubclass(numpy.dtype('int32').type, numbers.Integral)
assert not issubclass(numpy.dtype('float32').type, numbers.Integral)
于 2017-03-13T17:41:47.693 回答
5

由于提出了这个问题,NumPy 已经添加了适当的注册numbers,所以这有效:

issubclass(np.int64, numbers.Integral)
issubclass(np.int64, numbers.Real)
issubclass(np.int64, numbers.Complex)

这比深入到更深奥的 NumPy 界面更优雅。

要对 dtype 实例执行此检查,请使用其.type属性:

issubclass(array.dtype.type, numbers.Integral)
issubclass(array.dtype.type, numbers.Real)
issubclass(array.dtype.type, numbers.Complex)
于 2020-05-28T00:44:31.993 回答
0

根据用例,鸭子打字

import operator
int = operator.index(number)

在我看来是一个很好的方法。另外,它不需要任何特定的 numpy。

唯一的缺点是在某些情况下你必须try/except它。

于 2014-03-18T12:16:35.500 回答
-1

你是说17号线吗?

In [13]:

import numpy as np
A=np.array([1,2,3])
In [14]:

A.dtype
Out[14]:
dtype('int32')
In [15]:

isinstance(A, np.ndarray) #A is not an instance of int32, it is an instance of ndarray
Out[15]:
True
In [16]:

A.dtype==np.int32 #but its dtype is int32
Out[16]:
True
In [17]:

issubclass(np.int32, int) #and int32 is a subclass of int
Out[17]:
True
于 2014-03-18T06:34:16.900 回答