简体   繁体   English

numpy 2d其中每行有约束

[英]numpy 2d where with constraint on each row

I have a numpy array of shape (2,N) and three constraints to filter on. 我有一个形状(2,N)的numpy数组和三个要过滤的约束。

  1. No value in a column may be negative 列中的任何值都不能为负
  2. Row 0 must be less than a constant, say xmax 第0行必须小于常数,例如xmax
  3. Row 1 must be less than a constant, say ymax 第1行必须小于常数,例如ymax

Here is what I've tried: 这是我尝试过的:

xmax, ymax = 7, 8
dst = np.linspace(-2,10,20).reshape((2,-1)).astype(np.int32)
mask = np.where((0 <= dst) & (dst[1,:] < xmax) & (dst[0,:] < ymax))
mask = np.vstack(mask).T
for p in mask:
    print(p, dst[:,p[1]])

Which produces 哪个产生

(array([[-2, -1,  0,  0,  0,  1,  1,  2,  3,  3],
   [ 4,  4,  5,  6,  6,  7,  8,  8,  9, 10]]), (2L, 10L))
(array([0, 2]), array([0, 5]))
(array([0, 3]), array([0, 6]))
(array([0, 4]), array([0, 6]))
(array([1, 0]), array([-2,  4]))  #<-- Why do I get this ??
(array([1, 1]), array([-1,  4]))  #<-- Why do I get this ??
(array([1, 2]), array([0, 5]))
(array([1, 3]), array([0, 6]))
(array([1, 4]), array([0, 6]))

What am I doing wrong that is producing those two unwanted results (-2,4) and (-1,4)? 我在做那两个不需要的结果(-2,4)和(-1,4)的问题是什么?

As mentioned by @hpaulj, the mistake was in the where clause. 正如@hpaulj所提到的,错误出在where子句中。 I did not realize that I could treat this as a continuous boolean array. 我没有意识到我可以将其视为连续的布尔数组。 What I learned is that if I keep the dst >= 0 check, I maintain my dimensions and then I can add two more constraints to check for less than zero explicitly on each row value. 我了解到的是,如果我保持dst> = 0的检查,我会保持自己的尺寸,然后可以添加两个以上的约束来显式地检查每个行值是否小于零。

xmax, ymax = 7, 8
dst = np.linspace(-2,10,20).reshape((2,-1)).astype(np.int32)
mask = np.argwhere((dst >= 0) & (dst[0,:] >= 0) & (dst[1,:] >= 0) & (dst[1,:] < xmax) & (dst[0,:] < ymax))
print(mask)
for p in mask:
    print(p, dst[:,p[1]])
In [5]: xmax, ymax = 7, 8
   ...: dst = np.linspace(-2,10,20).reshape((2,-1)).astype(np.int32)
   ...: mask = np.where((0 <= dst) & (dst[1,:] < xmax) & (dst[0,:] < ymax))
   ...: 
In [6]: mask
Out[6]: 
(array([0, 0, 0, 1, 1, 1, 1, 1], dtype=int32),
 array([2, 3, 4, 0, 1, 2, 3, 4], dtype=int32))

In [8]: dst[mask]
Out[8]: array([0, 0, 0, 4, 4, 5, 6, 6])

mask does select the right elements of dst , but from either row. mask确实选择了dst的正确元素,但是从任一行中选择。

But this selects from both rows, using just part of the the mask info. 但这仅使用部分mask信息从两行中选择。 So it has some of the masked values, but also the value from the other row. 因此,它具有一些masked值,但也具有来自另一行的值。

In [9]: dst[:,mask[1]]
Out[9]: 
array([[ 0,  0,  0, -2, -1,  0,  0,  0],
       [ 5,  6,  6,  4,  4,  5,  6,  6]])
In [10]: dst[0,mask[1]]
Out[10]: array([ 0,  0,  0, -2, -1,  0,  0,  0])
In [11]: dst[1,mask[1]]
Out[11]: array([5, 6, 6, 4, 4, 5, 6, 6])

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

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