3

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?

1 Answer 1

7

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

the second solution is what I need. I was not aware of this in1d(). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.