简体   繁体   English

Numpy function 通过索引向量从 ndarray 中提取值

[英]Numpy function to extract values from ndarray by indices vector

I have a matrix mat of size (3, 5, 4) and a vector vec of size (4,) with indices corresponding to the first dimension of the matrix (ie between 0 and 2).我有一个大小为 (3, 5, 4) 的矩阵mat和一个大小为 (4,) 的向量vec ,其索引对应于矩阵的第一维(即介于 0 和 2 之间)。 I would like to extract an array of size (4, 5), which can be done via mat[vec, :, [True] * len(vec)] , but I was wondering if there is a more elegant solution using numpy functions without the need to create a new list of boolean values.我想提取一个大小为 (4, 5) 的数组,这可以通过mat[vec, :, [True] * len(vec)]来完成,但我想知道是否有使用 numpy 函数的更优雅的解决方案无需创建 boolean 值的新列表。

In [15]: mat = np.arange(3 * 5 * 4).reshape(3, 5, 4)
In [16]: idx = np.array([0, 2, 1, 1])

In [18]: mat[idx, :, [True] * len(idx)]
Out[18]: 
array([[ 0,  4,  8, 12, 16],
       [41, 45, 49, 53, 57],
       [22, 26, 30, 34, 38],
       [23, 27, 31, 35, 39]])

equivalent - whether it's more elegant?等效 - 它是否更优雅?

In [19]: mat[idx, :, np.arange(4)]
Out[19]: 
array([[ 0,  4,  8, 12, 16],
       [41, 45, 49, 53, 57],
       [22, 26, 30, 34, 38],
       [23, 27, 31, 35, 39]])

Unless you want a (4,5,4), you will have to provide equal size arrays for the 1st and 3rd dimensions.除非您想要 (4,5,4),否则您必须为第一个和第三个维度提供相同大小的 arrays。 There's no way around that.没有办法解决这个问题。

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

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