Pythonのnumpy.where()

numpy.where() 関数は、指定された条件が満たされる入力配列内の要素のインデックスを返します。

構文: numpy.where(条件[, x, y])
パラメーター:
状態 : True の場合は x が生成され、それ以外の場合は y が生成されます。
x、y: 選択する値。 x、y、および条件は、何らかの形状にブロードキャスト可能である必要があります。

戻り値:
外 : [ndarray または ndarray のタプル] x と y の両方が指定された場合、出力配列には、条件が True の場合は x の要素が含まれ、それ以外の場合は y の要素が含まれます。

条件のみが指定された場合は、タプルcondition.nonzero()、条件が True のインデックスを返します。

コード #1:




# Python program explaining> # where() function> > import> numpy as np> > np.where([[> True> ,> False> ], [> True> ,> True> ]],> > [[> 1> ,> 2> ], [> 3> ,> 4> ]], [[> 5> ,> 6> ], [> 7> ,> 8> ]])>

出力:

array([[1, 6], [3, 4]]) 

コード #2:




# Python program explaining> # where() function> > import> numpy as np> > # a is an array of integers.> a> => np.array([[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ]])> > print> (a)> > print> (> 'Indices of elements <4'> )> > b> => np.where(a <> 4> )> print> (b)> > print> (> 'Elements which are <4'> )> print> (a[b])>

出力:

[[1 2 3] [4 5 6]] Indices of elements  <4 (array([0, 0, 0], dtype=int64), array([0, 1, 2], dtype=int64)) Elements which are  <4 array([1, 2, 3])