简体   繁体   中英

2D NumPy array comparison in given range

If I have a 2D array of numbers and I want to see if every value inside the array are inside another 2D array of by some range, how would you do it efficiently with NumPy?

[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] is in range 1 with
[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] => TRUE

[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] is in range 1 with
[[0,3,0],[1,4,3],[1,4,5],[0,3,4],[0,4,3]] => TRUE

[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] is in range 1 with
[[0,4,0],[1,4,3],[1,4,5],[0,3,4],[0,4,3]] => FALSE

Last one is FALSE because on of the item on index 0.1 is 4 which means abs(2-4) > 1

You can do this easily with numpy's vectorized arithmetic and all . For example:

>>> a = np.array([[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]])
>>> b = np.array([[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]])
>>> abs(a-b)
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
>>> abs(a-b) <= 1
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> (abs(a-b) <= 1).all()
True

and

>>> a2 = np.array([[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]])
>>> b2 = np.array([[0,4,0],[1,4,3],[1,4,5],[0,3,4],[0,4,3]])
>>> abs(a2-b2) <= 1
array([[ True, False,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> (abs(a2-b2) <= 1).all()
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM