Tengis
Tengis

Reputation: 2809

Numpy: Indexing of arrays

Given the following example

d = array([[1, 2, 3],
           [1, 2, 3],
           [1, 3, 3],
           [4, 4, 4],
           [5, 5, 5]
          ])

To get the sub-array containing 1 in the first column:

d[ d[:,0] == 1 ]

array([[1, 2, 3],
       [1, 2, 3],
       [1, 3, 3]])

How to get (without loops) the sub-array containing 1 and 5? Shouldn't be something like

d[ d[:,0] == [1,5] ]  #   ---> array([1, 2, 3])

which does not work?

Upvotes: 3

Views: 109

Answers (1)

DSM
DSM

Reputation: 352959

Method #1: use bitwise or | to combine the conditions:

>>> d
array([[1, 2, 3],
       [1, 2, 3],
       [1, 3, 3],
       [4, 4, 4],
       [5, 5, 5]])
>>> (d[:,0] == 1) | (d[:,0] == 5)
array([ True,  True,  True, False,  True], dtype=bool)
>>> d[(d[:,0] == 1) | (d[:,0] == 5)]
array([[1, 2, 3],
       [1, 2, 3],
       [1, 3, 3],
       [5, 5, 5]])

Method #2: use np.in1d, which is probably easier if there are a lot of values:

>>> np.in1d(d[:,0], [1, 5])
array([ True,  True,  True, False,  True], dtype=bool)
>>> d[np.in1d(d[:,0], [1, 5])]
array([[1, 2, 3],
       [1, 2, 3],
       [1, 3, 3],
       [5, 5, 5]])

Upvotes: 7

Related Questions