我知道有一个简单的解决方案,但目前似乎无法找到它.
给定一个numpy数组,我需要知道数组是否包含整数.
检查dtype本身是不够的,因为有多个int dtypes(int8,int16,int32,int64 ...).
saf*_*fsd 48
在numpy书中找到它!第23页:
层次结构中的其他类型定义了特定类型的类型.这些类别可用于测试self.dtype.type返回的对象是否属于特定类(使用issubclass).
issubclass(n.dtype('int8').type, n.integer)
>>> True
issubclass(n.dtype('int16').type, n.integer)
>>> True
Run Code Online (Sandbox Code Playgroud)
Pet*_*r D 22
检查整数类型不适用于整数浮点数,例如,4.更好的解决方案np.equal(np.mod(x, 1), 0),如:
>>> import numpy as np
>>> def isinteger(x):
... return np.equal(np.mod(x, 1), 0)
...
>>> foo = np.array([0., 1.5, 1.])
>>> bar = np.array([-5, 1, 2, 3, -4, -2, 0, 1, 0, 0, -1, 1])
>>> isinteger(foo)
array([ True, False, True], dtype=bool)
>>> isinteger(bar)
array([ True, True, True, True, True, True, True, True, True,
True, True, True], dtype=bool)
>>> isinteger(1.5)
False
>>> isinteger(1.)
True
>>> isinteger(1)
True
Run Code Online (Sandbox Code Playgroud)
小智 8
这也有效:
n.dtype('int8').kind == 'i'
Run Code Online (Sandbox Code Playgroud)
Numpy的issubdtype()函数可以按如下方式使用:
import numpy as np
size=(3,3)
A = np.random.randint(0, 255, size)
B = np.random.random(size)
print 'Array A:\n', A
print 'Integers:', np.issubdtype(A[0,0], int)
print 'Floats:', np.issubdtype(A[0,0], float)
print '\nArray B:\n', B
print 'Integers:', np.issubdtype(B[0,0], int)
print 'Floats:', np.issubdtype(B[0,0], float)
Run Code Online (Sandbox Code Playgroud)
结果:
Array A:
[[ 9 224 33]
[210 117 83]
[206 139 60]]
Integers: True
Floats: False
Array B:
[[ 0.54221849 0.96021118 0.72322367]
[ 0.02207826 0.55162813 0.52167972]
[ 0.74106348 0.72457807 0.9705301 ]]
Integers: False
Floats: True
Run Code Online (Sandbox Code Playgroud)
PS。请记住,数组的元素总是具有相同的数据类型。