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 of ar1.
  • assume_unique (optional): This takes a logical value that indicates whether the arrays are assumed to be unique or not. Its default value is False.
  • invert (optional): It indicates which logical operator (TRUE or FALSE) is returned when an element of ar1 is present in ar2. TRUE is returned if the invert parameter is FALSE, and FALSE is returned if the invert parameter is TRUE.

Return value

The in1d() function returns boolean values as result.

Code example

import numpy as np
# creating input and test arrays
a = 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 a
print(np.in1d(a, b))

Explanation

  • Line 1: We import the numpy module.
  • Line 3–4: We create the input and test arrays, a and b, using the array() function.
  • Line 5–6: We print the two arrays, a and b.
  • Line 10: We check to see if the elements in b are present in a or not. Then we print the result to the console.

    Free Resources