Python 如何检查numpy数据类型是否为整数?
如何检查numpy数据类型是否为整数?我试过:Python 如何检查numpy数据类型是否为整数?,python,numpy,integer,abc,Python,Numpy,Integer,Abc,如何检查numpy数据类型是否为整数?我试过: issubclass(np.int64, numbers.Integral) 但它给出了False 更新:现在它给出了True你是说第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
issubclass(np.int64, numbers.Integral)
但它给出了False
更新:现在它给出了
True
你是说第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
请注意,
np.int64
不是数据类型,而是Python类型。如果您有一个实际的数据类型(通过数组的dtype
字段访问),您可以使用您发现的np.typecodes
dict:
my_array.dtype.char in np.typecodes['AllInteger']
如果您只有一个类型,例如np.int64
,则可以首先获取与该类型对应的数据类型,然后按上述方式查询:
>>> np.dtype(np.int64).char in np.typecodes['AllInteger']
True
Numpy有一个类似于类层次结构的数据类型层次结构(标量类型实际上有一个真正的类层次结构,它反映了数据类型层次结构)。您可以使用
np.issubdtype(some_dtype,np.integer)
测试数据类型是否为整数数据类型。请注意,与大多数使用数据类型的函数一样,np.issubdtype()
将其参数转换为数据类型,因此可以使用任何可以通过np.dtype()
构造函数生成数据类型的函数
在numpy的未来版本中,我们将确保标量类型使用适当的
数字注册。
abc。,具体取决于所使用的用例类型
import operator
int = operator.index(number)
在我看来,这是一个好方法。此外,它不需要任何具体的numpy
唯一的缺点是,在某些情况下,除了之外,您必须尝试/
。在前面的答案和评论的基础上,我决定将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)
自提出此问题以来,NumPy已添加了相应的注册号编号
,因此此功能有效:
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
有趣的是,实际上它只适用于int_
、intc
、intp
和int32
。我猜你在使用Python2?(对我来说,intp和int_u.是int64。)看起来它甚至依赖于平台/版本,我在Win32Python2.7.6
<代码>Numpy 1.8.1
。该文件提到,intc
和intp
可以是int32
或int64
,我相信。@downvoter请随时告诉我如何改进答案。我希望这不是被否决的答案,因为这是一个有用的答案。接下来,将标量类型注册到numbers
ABCs,因此issubclass(np.int32,numbers.Integral)
将工作,这要感谢。
issubclass(array.dtype.type, numbers.Integral)
issubclass(array.dtype.type, numbers.Real)
issubclass(array.dtype.type, numbers.Complex)