Remove All Occurrences of a Value from NumPy Array

This tutorial will discuss about unique ways to remove all occurrences of a value from numpy array.

Suppose we have an empire array of numbers,

numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35])

We want to delete all occurrences of value 35, from this array.

For this, we will compare the numpy array with value 35, using the == operator. It will return a boolean array where each True value denotes that the corresponding value in the original array is 35 and the value to be deleted.

numbers == valueToRemove

Then we will pass this boolean array to the where() function of numpy module. It will return a list of index position for which the boolean array contains True value, basically the index positions of the element to be deleted.

# Use the where() function to identify the
# indices of the elements to remove
indicesToRemove = np.where(numbers == valueToRemove)

Then we will call the numpy module’s delete() function. In which we will pass numpy array as first argument and the index positions of elements that need to be deleted as the second argument.

# Use the delete() function to remove
# the elements at the specified indices
numbers = np.delete(numbers, indicesToRemove)

It will return a copy of numpy array after deleting all the elements in the given index positions.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35])

# Define the value to remove
valueToRemove = 35

# Use the where() function to identify the
# indices of the elements to remove
indicesToRemove = np.where(numbers == valueToRemove)

# Use the delete() function to remove
# the elements at the specified indices
numbers = np.delete(numbers, indicesToRemove)

# Print the numpy array
print(numbers)

Output

[34 78 61 56 90]

Summary

We learned how to delete all occurrences of an item from NumPy Array in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top