これには簡単な解決策があることは知っていますが、現時点では見つけられないようです。
numpy 配列が与えられた場合、配列に整数が含まれているかどうかを知る必要があります。
複数の int dtype (int8、int16、int32、int64 ...) があるため、dtype 自体を確認するだけでは不十分です。
派手な本で見つけました!23ページ:
階層内の他のタイプは、タイプの特定のカテゴリを定義します。これらのカテゴリは、self.dtype.type によって返されるオブジェクトが特定のクラスのものであるかどうかをテストするのに役立ちます (issubclass を使用)。
issubclass(n.dtype('int8').type, n.integer)
>>> True
issubclass(n.dtype('int16').type, n.integer)
>>> True
整数型のチェックは、整数である float に対しては機能しません。たとえば、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
これも機能します:
n.dtype('int8').kind == 'i'
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)
結果:
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
PS。配列の要素は常に同じデータ型であることに注意してください。