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

时间:2016-01-18 16:21:36

标签: python arrays numpy comparison

如果我有一个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

最后一个是假的,因为索引0.1上的项目是4,这意味着abs(2-4)> 1

1 个答案:

答案 0 :(得分:2)

您可以使用numpy的矢量化算法和all轻松完成此操作。例如:

>>> 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

>>> 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