9

If you have array = np.array([1,2,3,4]) and you have index = np.array([0,1,2]) and you want to remove the index elements in array, what's the best way to do this without looping?

0

1 Answer 1

13

You use numpy.delete:

smaller_array = np.delete(array,index)
Sign up to request clarification or add additional context in comments.

2 Comments

+1 But for completeness, in this other question, @askewchan found out that building a boolean mask is faster than using np.delete, i.e mask = np.ones(array.shape, dtype=np.bool); mask[index] = False; smaller_array = array[mask].
The speed difference should mostly vanish, as delete will be basically a shorthand for that in 1.8. and later (with some faster paths for smaller slices and single integers). Until a bit longer there are some differences for out of bound/negative or boolean indices though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.