简体   繁体   English

使用 Numpy 从基于向量的 3D 矩阵中选择列

[英]Select columns from 3D matrix based on vector using Numpy

So I am trying to select some columns from a 3D matrix based on the values in a vector using Numpy.所以我试图根据使用 Numpy 的向量中的值从 3D 矩阵中选择一些列。 I have already solved the problem using a list comprehension, but I figured that there might be a better way using Numpy's builtin methods.我已经使用列表理解解决了这个问题,但我认为使用 Numpy 的内置方法可能有更好的方法。 Does anyone know if such a method or combination of methods exist?有谁知道是否存在这样的方法或方法的组合?

matrix1 = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])
matrix2 = np.array([[10, 11, 12],
                    [13, 14, 15],
                    [16, 17, 18]])
total_matrix = np.array([matrix1, matrix2])
vector = [0,1,1]

# Retrieve the first column from the first matrix, second and third from the second matrix.
result = np.array([total_matrix[index2,: , index1] for index1, index2 in enumerate(vector)]).transpose()

# result:
np.array([[1, 11, 12],
          [4, 14, 15],
          [7, 15, 18]])
In [58]: total_matrix[vector, np.arange(3)[:,None], np.arange(3)]
Out[58]: 
array([[ 1, 11, 12],
       [ 4, 14, 15],
       [ 7, 17, 18]])

vector indexes the first dimension. vector索引第一个维度。 The other 2 broadcast with it to select the required (3,3).另外2个广播用它来选择需要的(3,3)。 While I knew the general principle, I tried a number of variations (about 9) before getting the right one.虽然我知道一般原则,但在得到正确的一个之前,我尝试了许多变体(大约 9 个)。

The use of diagonal in the other answer is equivalent to doing:在另一个答案中使用diagonal相当于做:

In [61]: total_matrix[vector][:,np.arange(3),np.arange(3)]
Out[61]: 
array([[ 1,  5,  9],
       [10, 14, 18],
       [10, 14, 18]])

You can slice the total_matrix using your vector and then select appropriate diagonal elements of it:您可以使用您的vectortotal_matrix进行切片,然后选择它的适当对角线元素:

>>> np.diagonal(total_matrix[vector], axis1=0, axis2=2)
array([[ 1, 11, 12],
       [ 4, 14, 15],
       [ 7, 17, 18]])

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

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