numpy dtype が整数かどうかを確認するにはどうすればよいですか? 私は試した:
issubclass(np.int64, numbers.Integral)
しかし、それは与えFalse
ます。
更新: True
.
Numpy には、クラス階層に似た dtype の階層があります (スカラー型には、実際には dtype 階層を反映した正真正銘のクラス階層があります)。np.issubdtype(some_dtype, np.integer)
dtype が整数の dtype であるかどうかをテストするために使用できます。ほとんどのdtypeを消費する関数と同様np.issubdtype()
に、引数をdtypeに変換するため、コンストラクターを介してdtypeを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
numpy の将来のバージョンでは、スカラー型が適切なnumbers
ABC に登録されるようにします。
np.int64
これは dtype ではなく、Python の型であることに注意してください。実際の dtype (dtype
配列のフィールドを介してアクセス) がある場合は、np.typecodes
発見した dict を利用できます。
my_array.dtype.char in np.typecodes['AllInteger']
のようなタイプしかない場合はnp.int64
、まずそのタイプに対応する dtype を取得してから、上記のようにクエリを実行できます。
>>> np.dtype(np.int64).char in np.typecodes['AllInteger']
True
ユースケースに応じてダックタイピング
import operator
int = operator.index(number)
私の意見では良い方法です。さらに、派手な特定は何も必要ありません。
唯一の欠点は、場合によってはtry
/except
それをしなければならないことです。
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