Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于两个where子句访问二维数组的元素?_Python_Numpy_Multidimensional Array - Fatal编程技术网

Python 如何基于两个where子句访问二维数组的元素?

Python 如何基于两个where子句访问二维数组的元素?,python,numpy,multidimensional-array,Python,Numpy,Multidimensional Array,我有以下资料: [[ 3 271] [ 4 271] [375 271] [ 3 216] [375 216] [ 0 0] [ 0 546] [378 546] [378 0] [ 1 182] [ 2 181] [376 181] [377 182] [377 544] [376 545]] 基本上是一组X,Y坐标/点。我希望能够在两个轴上的给定点附近选择X,Y坐标 例如,给定一个目标点[3271],我首先检索该Y位置271处的所有其他点,

我有以下资料:

[[  3 271]
 [  4 271]
 [375 271]
 [  3 216]
 [375 216]
 [  0   0]
 [  0 546]
 [378 546]
 [378   0]
 [  1 182]
 [  2 181]
 [376 181]
 [377 182]
 [377 544]
 [376 545]]
基本上是一组X,Y坐标/点。我希望能够在两个轴上的给定点附近选择X,Y坐标

例如,给定一个目标点[3271],我首先检索该Y位置271处的所有其他点,然后能够选择X轴上的行-/+3。对于上述情况,这将产生:

[  3 271]
[  4 271]
我已经得到了所有具有相同Y值的行,如下所示:

index_on_y = points[:,1] == point[1]
shared_y = points[index_on_y]
这将返回:

shared_y:
[[  3 271]
 [  4 271]
 [375 271]]
如果X值列0可以是0-6之间的任何值,现在如何从该数组中选择所有行?我已经尝试过切片/索引/np的各种组合,但是没有得到想要的结果。以下是我得到的,但我知道它是不正确的;只是不知道正确和最有效的方法是什么:

def nearby_contour_points_x(self, point, points, radius):
    index_on_y = points[:,1] == point[1] # correct
    shared_y = points[index_on_y] # correct
    x_vals = shared_y[:,0] # not good?

    index_on_x = np.where(np.logical_or(x_vals <= (point[0] - radius), x_vals <= (point[0] + radius)))
    return shared_y[index_on_x]
理想情况下,我不必首先在其中一个轴上分组。

在您的示例中,使用a作为数组

target = np.array([3, 271])
减去目标

diff = a - target
y列1必须与目标相同-这将导致形状a的布尔数组。形状[0]:

y_rows = diff[:,1] == 0
x_rows = np.logical_and(diff[:,0] <= 6, diff[:,0] >= 0)
x在目标范围内-这将导致形状a的布尔数组。形状[0]:

y_rows = diff[:,1] == 0
x_rows = np.logical_and(diff[:,0] <= 6, diff[:,0] >= 0)
前面介绍了初始减法和更广义的一点:

x_rows = np.logical_and(a[:,0] >= target[0] - 3, a[:,0] <= target[0] + 3)
y_rows = a[:,1] == target[1]
mask = np.logical_and(x_rows, y_rows)
也许是对isclose的滥用,但确实有效

ys = np.array([[  3, 271],
 [  4, 271],
 [375, 271]])

np.compress(np.all(np.isclose(ys, [3,271], rtol=0, atol=3), axis=1), ys, axis=0)
Out[273]: 
array([[  3, 271],
       [  4, 271]])

非常感谢。最终结果给出了我想要的,但它也包括目标值本身。不过,这并不是一个真正的问题,假设它本身始终是返回数组中的第一个值。