如何使用每行的指定列从矩阵创建向量而不在 Python 中循环? [英] How can I create a vector from a matrix using specified colums from each row without looping in Python?
本文介绍了如何使用每行的指定列从矩阵创建向量而不在 Python 中循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个形状为 (N,d) 的矩阵和一个大小为 N 的向量,它表示矩阵中的哪一列与给定的行相关.如何返回由矩阵和相关列中的值给出的大小为 N 的向量?
Say I have a matrix of shape (N,d) and a vector of size N which says which column in the matrix is of relevance to a given row. How can I return the vector of size N which is given by the values in the matrix and the relevant column?
例如:
M = [[ 2, 4, 1, 8],
[3, 5, 7, 1],
[2, 5, 3, 9],
[1, 2, 3, 4]]
V = [2, 1, 0, 1]
我尝试了类似的东西:
M[:,V]
但这会返回一个 NXN 矩阵
but this returns a matrix which is NXN
是否有一种简单的方法来格式化它而不涉及编写 for 循环,以便我可以获得以下向量:
Is there a simple way to format this which does not involve writing a for-loop so that I could get the following vector:
V' = [1,5,2,2]
推荐答案
使用 np.arange(len(V))
索引行号,V
索引列:
Use np.arange(len(V))
for indexing the row numbers and V
for columns:
In [110]: M = [[ 2, 4, 1, 8],
.....: [3, 5, 7, 1],
.....: [2, 5, 3, 9],
.....: [1, 2, 3, 4]]
In [111]: V = [2, 1, 0, 1]
In [112]:
In [112]: M = np.array(M)
In [113]: M[np.arange(len(V)),V]
Out[113]: array([1, 5, 2, 2])
这篇关于如何使用每行的指定列从矩阵创建向量而不在 Python 中循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文