In this article we will discuss different ways to delete elements from a Numpy Array by matching value or based on multiple conditions.

Remove all occurrences of an element with given value from numpy array

Suppose we have a numpy array of numbers i.e.

Now suppose we want to delete all occurrences of 6 from the above numpy array. Let’s see how to do that,

Output:

How does this worked ?

Basically arr != 6 returned a bool array of same size as arr with True at places where value is not 6 and False at other places i.e.

Now if we pass this bool array to [] operator of numpy array arr, then it will select the elements from arr foe which bool array has True at corresponding index. Basically it returns the elements from arr which are not 6. Another point to be noted is that it returns a copy of existing array with elements with value 6. We can assign this new array back to arr to have the deletion effect of all occurrences of 6 from the numpy array.

Delete elements in Numpy Array based on multiple conditions

Suppose we have a numpy array of numbers i.e.

Now we want to delete all occurrences of elements below 6 & greater than 10 i.e. keep elements between range 6 to 10 only. Let’s see how to do that,

Output:

We basically created a bool array using multiple conditions on numpy array and then passed that bool array to [] operator of numpy array to select the elements only which satisfies the given conditions. So, it returned a copy of numpy array by selecting values below 6 & greater than 10 only and we assigned this new array back to arr to have the deletion effect.

Delete elements by value or condition using np.argwhere() & np.delete()

Suppose we have a numpy array of numbers i.e.

Now let’s delete all occurrences of 6 from the above numpy array using np.argwhere() & np.delete() i.e.

Output:

How did that worked ?

arr == 6 Returned a Numpy array of bool type with True at places where arr has 6 and False at other places. Size of this bool array will be equal to size of arr. Therefore contents of boolArr are,

Now pass this bool array to np.argwhere() which accepts a bool array and return the index positions where bool array has True value i.e.

Contents of indexArr are,

These are index positions from array arr where element value is 6. Now pass this index positions to np.delete() to delete elements from arra at given index positions i.e.

Output:

It deleted all occurrences of element with value 6.

Delete elements by multiple conditions using np.argwhere() & np.delete()

Contents of original Numpy array arr is,

Let’s delete all occurrences of elements between 6 to 10 in a single line i.e.

Output:

Complete example is as follows:

Output:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,