简体   繁体   English

给定范围内的2D NumPy数组比较

[英]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? 如果我有一个2D数字数组,并且想查看该数组中的每个值是否都在某个范围内的另一个2D数组中,那么如何使用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 最后一个为FALSE,因为索引0.1上的项的值为4,这意味着abs(2-4)> 1

You can do this easily with numpy's vectorized arithmetic and all . 您可以使用numpy的向量化算术和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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