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
a. All I know is the index of the values (
Use numpy.delete() - returns a new array with sub-arrays along an axis deleted
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) #Prints `[1, 2, 5, 6, 8, 9]`
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
"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) >>> c array([1, 2, 5, 6, 8, 9])