This tutorial will discuss about unique ways to remove elements from array that are 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 present in the otherArray
. Basically we want to delete the common 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 not present in otherArray mask = ~np.isin(mainArray, otherArray)
It will return a boolean array, where each True value denotes at the corresponding value in mainArray
is not 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 newArray = mainArray[mask]
Basically we selected only the elements from mainArray which were not present in the otherArray
.
Let’s see the complete example,
Frequently Asked:
- Remove elements from Array Greater than a Value in Python
- How to Remove Element from a NumPy Array?
- Remove Elements from a NumPy Array in a specific order
- How to Remove Smallest Element From a NumPy Array?
import numpy as np # Create a 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 not 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 newArray = mainArray[mask] # Print the numpy array print(newArray)
Output
[14 30 53]
Summary
We learned how to Remove Elements From a NumPy Array that are in Another NumPy Array in Python.