Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy: Comparing Elements in Two Arrays

Tags:

python

numpy

Anyone ever come up to this problem? Let's say you have two arrays like the following

a = array([1,2,3,4,5,6]) b = array([1,4,5]) 

Is there a way to compare what elements in a exist in b? For example,

c = a == b # Wishful example here print c array([1,4,5]) # Or even better array([True, False, False, True, True, False]) 

I'm trying to avoid loops as it would take ages with millions of elements. Any ideas?

Cheers

like image 566
ebressert Avatar asked Oct 23 '09 12:10

ebressert


People also ask

How do you compare elements of two NumPy arrays?

To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.

How do I compare values in two arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do I compare two arrays of different sizes Python?

pad the smaller array to be as long as the longer array, then substract one from the other and look with np. where((Arr1-Arr2)==0).


2 Answers

Actually, there's an even simpler solution than any of these:

import numpy as np  a = array([1,2,3,4,5,6]) b = array([1,4,5])  c = np.in1d(a,b) 

The resulting c is then:

array([ True, False, False,  True,  True, False], dtype=bool) 
like image 71
eteq Avatar answered Sep 29 '22 13:09

eteq


Use np.intersect1d.

#!/usr/bin/env python import numpy as np a = np.array([1,2,3,4,5,6]) b = np.array([1,4,5]) c=np.intersect1d(a,b) print(c) # [1 4 5] 

Note that np.intersect1d gives the wrong answer if a or b have nonunique elements. In that case use np.intersect1d_nu.

There is also np.setdiff1d, setxor1d, setmember1d, and union1d. See Numpy Example List With Doc

like image 29
unutbu Avatar answered Sep 29 '22 13:09

unutbu