如何检查numpy数据类型是否为整数?

2024-04-25 15:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如何检查numpy数据类型是否为整数?我试过:

issubclass(np.int64, numbers.Integral)

但它给出了False


更新:它现在给出True


Tags: numpyfalsetruenp整数数据类型numbersintegral
3条回答

Numpy有一个类似于类层次结构的数据类型层次结构(标量类型实际上有一个真实的类层次结构,它反映了数据类型层次结构)。可以使用np.issubdtype(some_dtype, np.integer)来测试数据类型是否为整数数据类型。请注意,与大多数使用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版本中,我们将确保标量类型注册到适当的numbersABCs。

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

import numbers
import numpy

assert issubclass(numpy.dtype('int32').type, numbers.Integral)
assert not issubclass(numpy.dtype('float32').type, numbers.Integral)

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

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

如果只有np.int64这样的类型,则可以首先获取与该类型相对应的数据类型,然后按上述方式进行查询:

>>> np.dtype(np.int64).char in np.typecodes['AllInteger']
True

相关问题 更多 >