简体   繁体   English

检查2D NumPy数组坐标的优雅方法在一定范围内

[英]Elegant way to check co-ordinates of a 2D NumPy array lie within a certain range

So let us say we have a 2D NumPy array (denoting co-ordinates) and I want to check whether all the co-ordinates lie within a certain range. 因此,假设我们有一个二维NumPy数组(表示坐标),我想检查所有坐标是否都在某个范围内。 What is the most Pythonic way to do this? 最Python化的方法是什么? For example: 例如:

a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])

#ALL THE COORDINATES WITHIN x-> 0 to 4 AND y-> 0 to 4 SHOULD
 BE PUT IN b (x and y ranges might not be equal)

b = #DO SOME OPERATION
>>> b
>>> [[3,4],
    [0,0]]

If the range is the same for both directions, x, and y, just compare them and use all : 如果两个方向(x和y)的范围相同,则将它们进行比较并使用all

import numpy as np

a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])
a[(a >= 0).all(axis=1) & (a <= 4).all(axis=1)]
# array([[3, 4],
#        [0, 0]])

If the ranges are not the same, you can also compare to an iterable of the same size as that axis (so two here): 如果范围不相同,您还可以比较与该轴大小相同的可迭代对象(此处为两个):

mins = 0, 1   # x_min, y_min
maxs = 4, 10  # x_max, y_max

a[(a >= mins).all(axis=1) & (a <= maxs).all(axis=1)]
# array([[1, 5],
#        [3, 4]])

To see what is happening here, let's have a look at the intermediate steps: 要查看此处发生的情况,让我们看一下中间步骤:

The comparison gives a per-element result of the comparison, with the same shape as the original array: 比较得出每个元素的比较结果,形状与原始数组相同:

a >= mins
# array([[False,  True],
#        [ True,  True],
#        [ True,  True],
#        [ True,  True],
#        [ True,  True],
#        [ True, False],
#        [False, False]], dtype=bool)

Using nmpy.ndarray.all , you get if all values are truthy or not, similarly to the built-in function all : 使用nmpy.ndarray.all ,您nmpy.ndarray.all所有值是否正确,类似于内置函数all

(a >= mins).all()
# False

With the axis argument, you can restrict this to only compare values along one (or multiple) axis of the array: 使用axis参数,可以将其限制为仅沿数组的一个(或多个)轴比较值:

(a >= mins).all(axis=1)
# array([False,  True,  True,  True,  True, False, False], dtype=bool)
(a >= mins).all(axis=0)
# array([False, False], dtype=bool)

Note that the output of this is the same shape as array, except that all dimnsions mentioned with axis have been contracted to a single True / False . 请注意,此输出与数组具有相同的形状,不同之处在于用axis提及的所有尺寸均已收缩为单个True / False

When indexing an array with a sequence of True, False values, it is cast to the right shape if possible. 在使用True, False值序列索引数组时,如果可能,将其转换为正确的形状。 Since we index an array with shape (7, 2) with an (7,) = (7, 1) index, the values are implicitly repeated along the second dimension, so these values are used to select rows of the original array. 由于我们用(7,) = (7, 1)索引索引形状为(7, 2) 7,2)的数组,因此这些值沿第二维隐式重复,因此这些值用于选择原始数组的行。

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

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