简体   繁体   English

numpy:为矩阵的每一列选择特定行的值

[英]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] yi1m之间。 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.

相关问题 基于特定列的值对 numpy 矩阵进行分组,仅在给定数组的行索引上 - Group numpy matrix based on value of particular column, only on row indices from given array Numpy从矩阵中提取行,列和值 - Numpy extract row, column and value from a matrix Numpy:将值插入到每行的不同列中 - Numpy: Insert value into different column for each row 如何为特定列的每个不同值选择一行并合并以在 Python 中形成新的数据框? - How to select one row for each distinct value for a particular column and merge to form a new dataframe in Python? 如何将字符串值分配给 numpy 数组中的特定行和列? - How to assign a string value to a particular row and column in numpy array? 如何基于numpy的矩阵中的值获取列,行号 - how to get column, row number based on value in matrix from numpy 在Numpy中将矩阵乘以另一个矩阵的每一行 - Multiply matrix by each row of another matrix in Numpy 矩阵的每一行和每一列中的最小值-Python - Minimum value in each row and each column of a matrix - Python 1 在由另一个 numpy 数组给出的特定列索引处的全零 numpy 数组的每一行中 - 1 in each row of an all zeros numpy array at particular column index given by another numpy array 无法将 numpy 行矩阵重塑为列矩阵 - Unable to reshape numpy row matrix into column matrix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM