简体   繁体   English

重塑/扩展numpy蒙版

[英]Reshaping/extending numpy mask

I want to select elements in b given a condition based on a . 我想选择的元素b给出了基于一个条件a However, the mask msk does not quite capture the output. 但是,掩码msk不能完全捕获输出。 Given the below, 鉴于以下情况,

>>> b = np.asarray([[[1, 11], [2, 12]], [[3, 13], [4, 14]], [[5, 15], [6, 16]], [[7, 17], [8, 18]]])
>>> b.shape
(4, 2, 2)
>>> b
array([[[ 1, 11],
        [ 2, 12]],

       [[ 3, 13],
        [ 4, 14]],

       [[ 5, 15],
        [ 6, 16]],

       [[ 7, 17],
        [ 8, 18]]])
>>> a = np.asarray([[0, 2], [3, 0], [0, 6], [0, 8]])
>>> a.shape
(4, 2)
>>> a
array([[0, 2],
       [3, 0],
       [0, 6],
       [0, 8]])
>>> msk = a > 0
>>> b[msk]
array([[ 2, 12],
       [ 3, 13],
       [ 6, 16],
       [ 8, 18]])
>>> msk
array([[False,  True],
       [ True, False],
       [False,  True],
       [False,  True]], dtype=bool)

I'd like to return [[11, 12], [3, 4], [15, 16], [17, 18]] instead of what b[msk] is currently returning. 我想返回[[11, 12], [3, 4], [15, 16], [17, 18]]而不是返回b[msk]当前返回的内容。 Intuitively, I think another dimension has to be added into msk converting it to the shape of b , ie (4, 2, 2) , but just calling msk.reshape didn't do the trick for me. 直观地,我认为必须向msk添加另一个维度,以将其转换为b的形状,即(4, 2, 2) msk.reshape (4, 2, 2) ,但是仅调用msk.reshape并不能解决我的问题。 I think with a mask like this, the problem would be solved. 我想用这样的口罩可以解决问题。 How can I convert the actual mask? 如何转换实际的面罩?

>>> msk
array([[[False,  True], [False,  True]],
       [[ True, False], [ True, False]],
       [[False,  True], [False,  True]],
       [[False,  True], [False,  True]]], dtype=bool)

Not sure if this is the best way, but: 不知道这是否是最好的方法,但是:

>>> transposed = np.transpose(b, (2, 0, 1))
>>> np.hstack((transposed[0][:, None], transposed[1][:, None]))[msk]
array([[11, 12],
       [ 3,  4],
       [15, 16],
       [17, 18]])

Edit: With OP's suggestion we can simplify it to: 编辑:根据OP的建议,我们可以将其简化为:

>>> np.transpose(b, (0, 2, 1))[msk]
array([[11, 12],
       [ 3,  4],
       [15, 16],
       [17, 18]])

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

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