What is the numpy.in1d() function in Python?
Overview
The in1d() function in Python is used to check if each element of a 1-D array is present in a second array.
Syntax
numpy.in1d(ar1, ar2, assume_unique=False, invert=False
Syntax for the in1d() function in Python
Parameters
The in1d() function takes the following parameter values:
ar1(required): This is the input array.ar2(required): The array against which to test each value ofar1.assume_unique(optional): This takes a logical value that indicates whether the arrays are assumed to be unique or not. Its default value isFalse.invert(optional): It indicates which logical operator (TRUEorFALSE) is returned when an element ofar1is present inar2.TRUEis returned if the invert parameter isFALSE, andFALSEis returned if the invert parameter isTRUE.
Return value
The in1d() function returns boolean values as result.
Code example
import numpy as np# creating input and test arraysa = np.array([1, 2, 3, 4, 5])b = np.array([1, 6, 2])print(a)print(b)# checking if the elements of b are found in aprint(np.in1d(a, b))
Explanation
- Line 1: We import the
numpymodule. - Line 3–4: We create the input and test arrays,
aandb, using thearray()function. - Line 5–6: We print the two arrays,
aandb. - Line 10: We check to see if the elements in
bare present inaor not. Then we print the result to the console.