如何检查 numpy dtype 是否是整数?我试过:
issubclass(np.int64, numbers.Integral)
但它给了False
。
更新:它现在给出True
.
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 的未来版本中,我们将确保标量类型已注册到适当的numbers
ABC。
请注意,这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
基于以前的答案和评论,我决定使用Python 的内置方法和模块type
的对象属性:dtype
issubclass()
numbers
import numbers
import numpy
assert issubclass(numpy.dtype('int32').type, numbers.Integral)
assert not issubclass(numpy.dtype('float32').type, numbers.Integral)
由于提出了这个问题,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)
根据用例,鸭子打字
import operator
int = operator.index(number)
在我看来是一个很好的方法。另外,它不需要任何特定的 numpy。
唯一的缺点是在某些情况下你必须try
/except
它。
你是说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