如何使用每行中的指定列从矩阵创建向量而无需在Python中循环? [英] How can I create a vector from a matrix using specified colums from each row without looping in Python?

查看:154
本文介绍了如何使用每行中的指定列从矩阵创建向量而无需在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-loop以便我可以获得以下向量:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆