# Remove Elements From a NumPy Array Based on a Mask

This tutorial will discuss about unique ways to remove elements from a numpy array based on a mask.

Suppose we have a numpy array of numbers,

# create sample numpy array
arr = np.array([20, 25, 15, 30, 22, 18])

Now we want to remove elements from this array based on a boolean array or a mask.

Suppose this is our boolean array,

mask = [False, True, True, True, False, False]

The size of this boolean array or mask should be equal to the size of the original numpy array. This boolean array contains certain True values and certain False values. Now if we pass this boolean array into the subscript operator of the number array like this,

# Use boolean indexing to remove
# elements from array

It will select only those values from the array for which this boolean sequence had True value. Basically, it will delete those values from the number array for which this mask had False value.

This way we can remove certain elements from a NumPy array based on a mask.

Let’s see the complete example,

import numpy as np

# create sample numpy array
arr = np.array([20, 25, 15, 30, 22, 18])

print('Original Array: ')
print(arr)

# create boolean mask for removing elements
mask = [False, True, True, True, False, False]

# Use boolean indexing to remove
# elements from array

print('Array after Removing elements:')
print(arr)

Output

Original Array:
[20 25 15 30 22 18]
Array after Removing elements:
[25 15 30]

## Summary

We learned how to remove elements from a NumPy Array nased on a mask in Python.

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

Scroll to Top