Home > Mobile >  Comparison between two numpy arrays in python
Comparison between two numpy arrays in python

Time:01-03

My objective is to check whether each row of a big array exists in a small array.

import numpy as np

big_array = np.array([[5, 0], [1, -2], [0, 2], [-1, 3], [1, 2]]) 
small_array = np.array([[0, 2], [5, 0]])

print([row in small_array for row in big_array])
-> [True, False, True, False, True]

It is obvious the last row of the big array [1, 2] is not included in the small array. But the result shows the opposite answer True.

If anyone knows the reason? Thanks!

CodePudding user response:

Let's do the example: np.array([1, 2]) in small_array

It will check if the 1 is anywhere in the small array in the first position (index 0). It is not. Then it checks if the 2 is anywhere in the small array in the second position (index 1). It is! As one of the two returns True, it will return True.

So np.array([i, 2]) in small_array will always return True for any i.

  • Related