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.
Answer from Levon on Stack OverflowUse 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.
Use np.setdiff1d:
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)
>>> c
array([1, 2, 5, 6, 8, 9])
python - Removing certain element indexes in numpy array - Stack Overflow
python - Delete elements of numpy array by indexes - Stack Overflow
Trying to add 1 to the element at a certain index of a numpy array
how can I remove rows from a numpy array based on a condition
In this particular case you can use slicing:
after = before[:,::2]
Note, this creates a new np.ndarray object that is a view over the original buffer.
A more general approach might be something like:
after = np.delete(before, [1, 3], axis=1)
This shouldn't be a view over the original buffer.
You can select the column you want to keep:
after = before[:, [0, 2, 4]]
[[1 5 1]
[1 5 3]
[1 5 0]
[1 2 9]
[8 4 7]]