Remove items in Array that are not in Another Array in Python

This tutorial will discuss about unique ways to remove elements from array that are not in another array – Python.

Suppose we have two NumPy Arrays,

mainArray = np.array([14, 23, 30, 41, 53])
otherArray = np.array([23, 41])

Now we want to remove only those elements from the mainArray which are not present in the otherArray. Basically we want to keep the common values and delete all the or different values from the mainArray.

We will create a boolean mask, equal to the size of the mainArray using the numpy.isin() function. In which we will pass both the arrays as arguments.

# Create a boolean mask equal to the size of mainArray
# Each True value in mask denotes that the corresponding
# value from mainArray is present in otherArray
mask = np.isin(mainArray, otherArray)

It will return a boolean array, where each True value denotes at the corresponding value in mainArrayis present in the otherArray. Then using the mask we will select only those values from the mainArray where this boolean sequence contains True value.

# Use the mask to select only those values from mainArray
# where mask contains the True value at respective place
mainArray = mainArray[mask]

Basically we selected only the elements from mainArray which were present in the otherArray.

Let’s see the complete example,

import numpy as np

# Create two NumPy Arrays
mainArray = np.array([14, 23, 30, 41, 53])
otherArray = np.array([23, 41])

# Create a boolean mask equal to the size of mainArray
# Each True value in mask denotes that the corresponding
# value from mainArray is present in otherArray
mask = np.isin(mainArray, otherArray)

# Use the mask to select only those values from mainArray
# where mask contains the True value at respective place
mainArray = mainArray[mask]

# Print the numpy array
print(mainArray)

Output

[23 41]

Summary

We learned how to Remove Elements From a NumPy Array that are not present in Another 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