# numpy np.intersect1d : Get Intersection of two or more arrays in Python

Numpy is the best python package for creating an array. There are many methods in it that allow you to do complex mathematical calculations in an efficient way. Numpy np.intersect1d() is one of them.

In this entire tutorial, you will learn how to find the intersection of two or more NumPy arrays in python.

## What is NP intersect1d?

Numpy provides a method np.intersect1d that allows you to calculate the intersection of two or more NumPy arrays. The syntax for this method is below.

numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)

The explanation of the parameters is below.

ar1: First Input array.

ar2: Second input array.

assume_unique:  The input arrays are both assumed to be unique if it is set to true. It increases the speed of the calculation. The default value is false.

return_indices: If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.

## How do you find the intersection of two NumPy arrays?

Let’s find the intersection of two Numpy arrays using the NumPy.intersect1d(). Firstly, you will create two-sample NumPy arrays and pass these two arrays as an argument to find the intersection or common elements of the two NumPy arrays.

Execute the full lines of code to find the intersection of two NumPy arrays.

import numpy as np
array1 = np.array([10,20,30,40,50])
array2 = np.array([20,40,50,60])
print(np.intersect1d(array1,array2))

Output

## Find the intersection of more than two NumPy arrays?

The first case finds the intersection of two NumPy arrays. But what if you want to find an intersection of more than two arrays. You cannot directly pass all these arrays as an argument of the np.intersect1d() method.

For this case you have to use functools.reduce . The functools.reduce will store the results of the intersection of two arrays and then find the intersection of other arrays using it.

Run the following lines of code to find the intersection of three NumPy arrays.

import numpy as np
from functools import reduce
# more than 2 array
array1 = np.array([10,20,30,40,50])
array2 = np.array([20,40,50,60])
array3 = np.array([10,20])
print(reduce(np.intersect1d,(array1,array2,array3)))

Output

## Conclusion

These are the ways to find the intersection of two and three NumPy arrays using the numpy.intersect1d() method. I hope you have liked this tutorial.

If you have any queries then you can contact us for more help.

Reference:

Numpy Documentation