+1 vote
in Programming Languages by (75.9k points)

Is there any function to delete an element or elements from a numpy array? I tried the remove() function, but it did not work.

1 Answer

+2 votes
by (60.0k points)
selected by
Best answer

The remove() function is for Python list, and it does not work for numpy array. You need to use the delete() function to remove an element or elements from a numpy array. In this function, you need to provide the list and the indices of the elements that you want to delete as arguments. It returns a new array, i.e., the old array will not change.

Here is an example to show how to delete one element or multiple elements. I am using numpy where() function to find the index of an element and the isin() function to find the indices of multiple elements.

>>> import numpy as np

>>> aa=np.asarray([12,32,43,34,56,89])

>>> aa

array([12, 32, 43, 34, 56, 89])

>>> a1=np.delete(aa, np.where(aa==43))

>>> a1

array([12, 32, 34, 56, 89])

>>> a2=np.delete(aa, np.isin(aa,[12,56]).nonzero()[0])

>>> a2

array([32, 43, 34, 89])