[英]Numpy: select value at a particular row for each column of a matrix
I have a 2D matrix X = ((a11, a12, .. a1n), (a21 .. a2n) .. (am1, .. amn))
and a 1D vector y = [y1, ..., yn]
each yi
is between 1
and m
. 我有一个2D矩阵X = ((a11, a12, .. a1n), (a21 .. a2n) .. (am1, .. amn))
和一个1D向量y = [y1, ..., yn]
yi
在1
到m
之间。 For each column i
of X
I want to pick out the element at row yi
. 对于X
i
列,我想选择第yi
行的元素。 That is, I want to pick out the vector z = (a_(y1 1), ... a_(yn n))
. 也就是说,我要挑选向量z = (a_(y1 1), ... a_(yn n))
。
Is there a vectorized way to do this? 有矢量化的方法可以做到这一点吗?
How about this: 这个怎么样:
In [39]: x = np.arange(12).reshape(4,3)
In [40]: y = np.array([0,3,2])
In [41]: x[y[None, :], np.arange(len(y))[None,:]][0]
Out[41]: array([ 0, 10, 8])
In [42]: x
Out[42]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
As an alternative solution, np.choose
is useful for making the selections. 作为替代解决方案, np.choose
可用于进行选择。
>>> x = np.arange(16).reshape(4,4)
So x
looks like this: 所以x
看起来像这样:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Now the selection of the value at a particular row y
in each column can be done like this: 现在,可以像这样完成每一列中特定行y
的值选择:
>>> y = np.array([3, 0, 2, 1])
>>> np.choose(y, x)
array([12, 1, 10, 7])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.