I am looking for the optimal (fastest) way to find the exact overlap between two arrays in numpy. Given two arrays x and y
x = array([1,0,3,0,5,0,7,4],dtype=int)
y = array([1,4,0,0,5,0,6,4],dtype=int)
What I want to get is, an array of the same length that contains only the numbers from both vectors that are equal:
array([1,0,0,0,5,0,0,4])
First I tried
x&y
array([1,0,0,0,5,0,6,4])
Then I realised that this is always true for two numbers if they are > 0.
Have a look at
numpy.wheredocumentation for explanation. Basically,numpy.where(a, b, c), for a conditionareturns an array of shapea, and with values fromborc, depending upon whether the corresponding element ofais true or not.borccan be scalars.By the way,
x & yis not necessarily “always true” for two positive numbers. It does bitwise-and for elements inxandy:This is because the bitwise representation of each element in
xis of the form1followed bynzeros, and the corresponding element inyisn1s. In general, for two non-zero numbersaandb,a & bmay equal zero, or non-zero but not necessarily equal to eitheraorb.