How to make such an array of equality fast (in numpy)?

I have two numpy arrays (2 dimensional), for example

a1 = array([["a","b"],["a","c"],["b","b"],["a","b"]])
a2 = array([["a","b"],["b","b"],["c","a"],["a","c"]])

What is the most elegant way to get such a matrix:

array([[1,0,0,0],
       [0,0,0,1],
       [0,1,0,0],
       [1,0,0,0]])

If the element (i, j) is equal to 1, if all (a1 [i ,:] == a2 [j ,:]) and otherwise 0

(I do not consider everything connected with two cycles elegant)

+5
source share
1 answer
>>> (a1[:,numpy.newaxis] == a2).all(axis=2)
array([[ True, False, False, False],
       [False, False, False,  True],
       [False,  True, False, False],
       [ True, False, False, False]], dtype=bool)

If you really need integers, go in intas a last step:

>>> (a1[:,numpy.newaxis] == a2).all(axis=2).astype(int)
array([[1, 0, 0, 0],
       [0, 0, 0, 1],
       [0, 1, 0, 0],
       [1, 0, 0, 0]])
+10
source

All Articles