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?

mgilson
  • 300,191
  • 65
  • 633
  • 696
lord12
  • 2,837
  • 9
  • 35
  • 47

1 Answers1

13

You use numpy.delete:

smaller_array = np.delete(array,index)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    +1 But for completeness, in [this other question](http://stackoverflow.com/a/15706171/110026), @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]`. – Jaime Apr 01 '13 at 20:11
  • 4
    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. – seberg Apr 01 '13 at 21:33