0

I have the following array and a list of indices

my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])

I can get the values of the array corresponding to my indices by just doing my_array[indices], which gives me the expected result

array([[1, 2],
       [5, 6]])

Now I want to get the complement of it. As mentioned in one of the answers, doing

my_array[~indices]

Will not give the expected result [[3,4],[7,8]].

I was hoping this could be done in a 1-liner way, without having to define additional masks.

0

1 Answer 1

2

You can use numpy.delete. It returns a new array with sub-arrays along an axis deleted.

complement = np.delete(my_array, indices, axis=0)
>>> np.delete(my_array, indices, axis=0)
array([[3, 4],
       [7, 8]])
Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain why the intuitive ~ returns unexpected result?
Why on earth would ~ (bitwise inverse) give the expected result?
@JonasPalačionis A simple reason is that arr.shape == (~arr).shape, which is clearly not what we need here.
Thank you Riccardo for answering in a kind and explicative way!

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.