0

I have an array arr and a list of indices that I want to get indices. I want to get subset of array corresponding to items in indices and the complement of that.

For example

for

arr = np.asarray([2, 4, 1, 5, 6])
indices = np.asarray([2, 4])

I would get

[1, 6] and [2, 4, 5]

Thanks

4
  • Ok, I give up. Where does the [2, 4, 5] come from in your result? Commented May 9, 2019 at 17:25
  • it is a complement . you return items given by indices and delete these items from an original array (or it can be any there way of giving complement Commented May 9, 2019 at 17:41
  • is your arr a numpy array? If so, please edit your code accordingly Commented May 9, 2019 at 17:43
  • @Mstaino edited Commented May 9, 2019 at 17:52

1 Answer 1

2

Using np.isin or np.in1d (using masks):

arr = np.asarray([2, 4, 1, 5, 6])
indices = np.asarray([2, 4])
m = np.in1d(np.arange(len(arr)), indices)
arr1, arr2 = arr[m], arr[~m]
arr1, arr2
>>array([1, 6]), array([2, 4, 5])

Alternatively, using np.setdiff1d for the complementary part (can be faster for larger arrays and indices):

arr1 = arr[indices]
arr2 = arr[np.setdiff1d(np.arange(len(arr)), indices, True)]
Sign up to request clarification or add additional context in comments.

Comments

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.