简体   繁体   English

pythonic根据遮罩从3d数组中提取切片的方法

[英]pythonic way to extract a slice from 3d array according to mask

I have an MxNxD array I and also a binary MxN mask M. 我有一个MxNxD数组I和一个二进制MxN掩码M。

Let's say that there are k 1s in M. What I want is to extract a kxD array that contains all the D-length vectors corresponding to the 1s in the mask. 假设M中有k 1个。我想要提取一个kxD数组,其中包含与掩码中的1s对应的所有D长度向量。

I can get the indices of these vectors in I by calling numpy.nonzero() but I can't find a nice compact way of getting my slice without horrible loops. 我可以通过调用numpy.nonzero()来获取这些向量的索引,但找不到一种没有可怕循环的切片的简便方法。

Any help will be much appreciated. 任何帮助都感激不尽。

I think this is what you want: 我认为这是您想要的:

In [283]: A = np.arange(24).reshape(2,3,4)
In [284]: M = np.array([[1,0,1],[0,1,0]],dtype=bool)
In [285]: A
Out[285]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [286]: M
Out[286]: 
array([[ True, False,  True],
       [False,  True, False]])
In [287]: I,J = np.nonzero(M)
In [288]: I,J
Out[288]: (array([0, 0, 1]), array([0, 2, 1]))
In [289]: A[I,J,:]
Out[289]: 
array([[ 0,  1,  2,  3],
       [ 8,  9, 10, 11],
       [16, 17, 18, 19]])

Since M is masking the initial dimensions, it can be simplified to 由于M遮盖了初始尺寸,因此可以简化为

A[np.nonzero(M)]

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

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