如何检查numpy数据类型是否为整数?
我怎么检查一个numpy的数据类型是不是整数类型呢?我试过:
issubclass(np.int64, numbers.Integral)
但是它返回的是 False
。
更新:现在它返回的是 True
。
6 个回答
根据不同的使用场景,我觉得鸭子类型(duck typing)是一种不错的方法。
import operator
int = operator.index(number)
而且它不需要任何特定于numpy的东西。
唯一的缺点是,在某些情况下,你可能需要使用try
/except
来处理错误。
在之前的回答和评论的基础上,我决定使用Python内置的issubclass()
方法,以及numbers
模块中的dtype
对象的type
属性。
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接口要优雅得多。
要在一个数据类型实例上进行这个检查,可以使用它的.type
属性:
issubclass(array.dtype.type, numbers.Integral)
issubclass(array.dtype.type, numbers.Real)
issubclass(array.dtype.type, numbers.Complex)
请注意,np.int64
不是一种数据类型,而是 Python 的一种类型。如果你有一个实际的数据类型(可以通过数组的 dtype
字段访问),你可以使用你发现的 np.typecodes
字典:
my_array.dtype.char in np.typecodes['AllInteger']
如果你只有像 np.int64
这样的类型,你可以先获取一个与该类型对应的数据类型,然后像上面那样查询它:
>>> np.dtype(np.int64).char in np.typecodes['AllInteger']
True
Numpy有一个数据类型的层级结构,类似于类的层级结构(其实标量类型确实有一个真实的类层级,和数据类型的层级相对应)。
在Numpy 2.0及以上版本中,你应该使用 np.isdtype
:比如 np.isdtype(np.void, 'integral')
。
如果不是这样,你可以用 np.issubdtype(some_dtype, np.integer)
来检查某个数据类型是否是整数类型。需要注意的是,像大多数处理数据类型的函数一样,np.issubdtype()
会把它的参数转换成数据类型,所以任何可以通过 np.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
另外,标量类型现在已经和相应的 numbers
ABCs 注册在一起了。