1 つ以上の条件に基づいて NumPy 配列から要素を選択することは、NumPy の美しく高密度の構文を使用して簡単です。
>>> import numpy as NP
>>> # generate a matrix to demo the code
>>> A = NP.random.randint(0, 10, 40).reshape(8, 5)
>>> A
array([[6, 7, 6, 4, 8],
[7, 3, 7, 9, 9],
[4, 2, 5, 9, 8],
[3, 8, 2, 6, 3],
[2, 1, 8, 0, 0],
[8, 3, 9, 4, 8],
[3, 3, 9, 8, 4],
[5, 4, 8, 3, 0]])
列 2 で 6 より大きい要素はいくつありますか?
>>> ndx = A[:,1] > 6
>>> ndx
array([False, True, False, False, True, True, True, True], dtype=bool)
>>> NP.sum(ndx)
5
A の最後の列の絶対値が 3 より大きい要素はいくつありますか?
>>> A = NP.random.randint(-4, 4, 40).reshape(8, 5)
>>> A
array([[-4, -1, 2, 0, 3],
[-4, -1, -1, -1, 1],
[-1, -2, 2, -2, 3],
[ 1, -4, -1, 0, 0],
[-4, 3, -3, 3, -1],
[ 3, 0, -4, -1, -3],
[ 3, -4, 0, -3, -2],
[ 3, -4, -4, -4, 1]])
>>> ndx = NP.abs(A[:,-1]) > 3
>>> NP.sum(ndx)
0
A の最初の 2 行で 2 以上の要素はいくつあるか?
>>> ndx = A[:2,:] >= 2
>>> NP.sum(ndx.ravel()) # 'ravel' just flattens ndx, which is originally 2D (2x5)
2
NumPy のインデックス構文は R にかなり近いです。R の流暢さを考えると、このコンテキストでの R と NumPy の主な違いは次のとおりです。
NumPyインデックスは 0 ベースです。R では、インデックスは 1 から始まります。
NumPy (Python など) では、負のインデックスを使用して右から左にインデックスを付けることができます。
# to get the last column in A
A[:, -1],
# to get the penultimate column in A
A[:, -2]
# this is a big deal, because in R, the equivalent expresson is:
A[, dim(A)[0]-2]
NumPy はコロン ":" 表記を使用して "unsliced" を示します。たとえば、R では、A の最初の 3 行を取得するには、A[1:3, ] を使用します。NumPy では、A[0:2, :] を使用します (NumPy では、「0」は必要ありません。実際には、A[:2, :] を使用することをお勧めします)。