check for identical rows in different numpy arrays

  • A+

how do I get a row-wise comparison between two arrays, in the result of a row-wise true/false array?

Given datas:

a = np.array([[1,0],[2,0],[3,1],[4,2]]) b = np.array([[1,0],[2,0],[4,2]]) 

Result step 1:

c = np.array([True, True,False,True]) 

Result final:

a = a[c] 

So how do I get the array c ????

P.S.: In this example the arrays a and b are sorted, please give also information if in your solution it is important that the arrays are sorted


Here's a vectorised solution:

res = (a[:, None] == b).all(-1).any(-1)  print(res)  array([ True,  True, False,  True]) 

Note that a[:, None] == b compares each row of a with b element-wise. We then use all + any to deduce if there are any rows which are all True for each sub-array:

print(a[:, None] == b)  [[[ True  True]   [False  True]   [False False]]   [[False  True]   [ True  True]   [False False]]   [[False False]   [False False]   [False False]]   [[False False]   [False False]   [ True  True]]] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: