Reputation: 990
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
Upvotes: 0
Views: 240
Reputation: 353059
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
Upvotes: 2