0

Given an index array idx that only contains 0 and 1 elements, and 1s represent the sample indices of interest, and a sample array A (A.shape[0] = idx.shape[0]). The objective here is to extract a subset of samples based on the index vector.

In matlab, it is trivial to do:

B = A(idx,:) %assuming A is 2D matrix and idx is a logical vector

How to achieve this in Python in a simple manner?

2
  • 1
    A[idx.astype(bool)] I suppose? Commented Jan 14, 2018 at 23:40
  • 1
    @cᴏʟᴅsᴘᴇᴇᴅ: You gave the answer!! Thanks! Commented Jan 14, 2018 at 23:43

2 Answers 2

4

If your mask array idx has the same shape as your array A, then you should be able to extract elements specified by the mask if you convert idx to a boolean array, using astype.

Demo -

>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> idx
array([[1, 0, 0, 1, 1],
       [0, 0, 0, 1, 0],
       [1, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [0, 1, 1, 1, 1]])

>>> A[idx.astype(bool)]
array([ 0,  3,  4,  8, 10, 13, 14, 15, 18, 19, 21, 22, 23, 24])
Sign up to request clarification or add additional context in comments.

Comments

1

Using the bool operation is equivalent to that logical one in Matlab:

B = A[idx.astype(bool)]

1 Comment

The : is redundant here, so you don't really need it. Also, I didn't downvote.

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.