python创建矩阵行向量_如何使用每行中的指定列从矩阵创建向量而无需在Python中循环?...

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?

For example:

M = [[ 2, 4, 1, 8],

[3, 5, 7, 1],

[2, 5, 3, 9],

[1, 2, 3, 4]]

V = [2, 1, 0, 1]

I tried something like:

M[:,V]

but this returns a matrix which is NXN

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]

解决方案

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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值