37

numpy dtype が整数かどうかを確認するにはどうすればよいですか? 私は試した:

issubclass(np.int64, numbers.Integral)

しかし、それは与えFalseます。


更新: True.

4

6 に答える 6

64

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 の将来のバージョンでは、スカラー型が適切なnumbersABC に登録されるようにします。

于 2014-03-18T10:16:45.893 に答える
18

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
于 2014-03-18T07:17:58.560 に答える
0

ユースケースに応じてダックタイピング

import operator
int = operator.index(number)

私の意見では良い方法です。さらに、派手な特定は何も必要ありません。

唯一の欠点は、場合によってはtry/exceptそれをしなければならないことです。

于 2014-03-18T12:16:35.500 に答える
-1

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
于 2014-03-18T06:34:16.900 に答える