numpy.intersect1d#

numpy.intersect1d(ar1,ar2,assume_unique=False,return_indices=False)[source]#

Find the intersection of two arrays.

Return the sorted, unique values that are in both of the input arrays.

Parameters:
ar1, ar2array_like

Input arrays. Will be flattened if not already 1D.

assume_uniquebool

If True, the input arrays are both assumed to be unique, whichcan speed up the calculation. If True butar1 orar2 are notunique, incorrect results and out-of-bounds indices could result.Default is False.

return_indicesbool

If True, the indices which correspond to the intersection of the twoarrays are returned. The first instance of a value is used if there aremultiple. Default is False.

Returns:
intersect1dndarray

Sorted 1D array of common and unique elements.

comm1ndarray

The indices of the first occurrences of the common values inar1.Only provided ifreturn_indices is True.

comm2ndarray

The indices of the first occurrences of the common values inar2.Only provided ifreturn_indices is True.

Examples

>>>importnumpyasnp>>>np.intersect1d([1,3,4,3],[3,1,2,1])array([1, 3])

To intersect more than two arrays, use functools.reduce:

>>>fromfunctoolsimportreduce>>>reduce(np.intersect1d,([1,3,4,3],[3,1,2,1],[6,3,4,2]))array([3])

To return the indices of the values common to the input arraysalong with the intersected values:

>>>x=np.array([1,1,2,3,4])>>>y=np.array([2,1,4,6])>>>xy,x_ind,y_ind=np.intersect1d(x,y,return_indices=True)>>>x_ind,y_ind(array([0, 2, 4]), array([1, 0, 2]))>>>xy,x[x_ind],y[y_ind](array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
On this page