How to remove specific elements in a numpy array

arrays, numpy, python

Solution

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

numpy.delete(a, index)

For your specific question:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]

new_a = np.delete(a, index)

print(new_a)
# Output: [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.

Problem

How can I remove some specific elements from a numpy array? Say I have ``` import numpy as np a = np.array([1,2,3,4,5,6,7,8,9]) ``` I then want to remove `3,4,7` from `a`. All I know is the index of the values (`index=[2,3,6]`).

Original source