Python

NumPy Np.Intersect1d()

The NumPy intersect1d() function allows you to fetch the common elements between two arrays.

Let us explore this function further.

Function Syntax

The function syntax is as shown in the code below:

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

Function Parameters

The function parameters are as follows:

  1. ar1 and ar2 – refer to the input arrays. If the arrays are not one-dimensional, the function will flatten to 1D and determine the intersection.
  2. assume_unique – this is a Boolean value that states whether both arrays are to be treated as unique. The default value is set to false.
  3. return_indicies – if set to true, the function will return an array of the indices of the intersecting values in the two arrays.

Function Return Value

The function returns a 1d array containing unique and common elements between the two arrays.

If the return_indices parameter is true, the function will also return an array holding the intersecting elements in the two arrays.

Example #1

The following example shows how to use the intersect1d() function with a one-dimension array.

1
2
3
# import numpy
import numpy as np
print(np.intersect1d([1,2,3,4], [4,3,10,2]))

In this example, the function should return the common and unique elements between the two arrays.

The resulting array is as shown:

1
[2 3 4]

Example #2

To get the indices of the common elements between the two arrays, we can do:

1
print(np.intersect1d([1,2,3,4], [4,3,10,2], return_indices=True))

The above code should return an array of the familiar and unique elements and two other arrays holding the indices of the common elements in each array.

An example output is as shown:

1
(array([2, 3, 4]), array([1, 2, 3], dtype=int64), array([3, 1, 0], dtype=int64))

Example #3

Take a look at the example shown below that shows how the function works on a two-dimensional array.

1
2
3
arr1 = np.array([[1,2,3,4], [5,6,7,8]])
arr2 = np.array([[6,4,3,2], [1,0,9,10]])
print(np.intersect1d(arr1, arr2, assume_unique=True))

In this example, we tell the function to treat both arrays as unique. This can help to speed up the calculations.

NOTE: Do not set the assume_unique parameter if both arrays are not unique. This may lead to incorrect values or out-of-bound indices errors.

Conclusion

Thank you for reading this article. This guide explored the intersect1d() function, its syntax, and how it works given various inputs.

See you at the next one!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list