How to remove specific elements in a numpy array How to remove specific elements in a numpy array python python

How to remove specific elements in a numpy array


Use numpy.delete() - returns a new array with sub-arrays along an axis deleted

numpy.delete(a, index)

For your specific question:

import numpy as npa = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])index = [2, 3, 6]new_a = np.delete(a, index)print(new_a) #Prints `[1, 2, 5, 6, 8, 9]`

Note that numpy.delete() returns a new array since array scalars are immutable, similar to strings in Python, so each time a change is made to it, a new object is created. I.e., to quote the delete() docs:

"A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place..."

If the code I post has output, it is the result of running the code.


There is a numpy built-in function to help with that.

import numpy as np>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])>>> b = np.array([3,4,7])>>> c = np.setdiff1d(a,b)>>> carray([1, 2, 5, 6, 8, 9])


A Numpy array is immutable, meaning you technically cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:

b = np.delete(a, [2,3,6])


matomo