[英]How to select different columns from each row in nd-array in Python/numpy?
Suppose I have 3 x 2 matrix 假设我有3 x 2矩阵
A = np.arange(3*2).reshape(3,2)
and wish to select elements by index array 并希望通过索引数组选择元素
I = [0, 1, 0]
to get 要得到
[[0],[3],[4]]
How would I do this? 我该怎么做?
Writing this way 这样写
A[:,[0,1,0]]
gives something completely different (what?) 给出了完全不同的东西(什么?)
What you can do is pass an iterable of the first dimesion value, and an iterable (eg a list) of the second dimension. 你可以做的是通过第一dimesion值的迭代 ,第二个维度的迭代 (如表)。 Something like:
就像是:
I = [0, 1, 0]
A[range(len(I)),I]
This produces: 这会产生:
>>> A[range(len(I)),I]
array([0, 3, 4])
In case you want it as a 2d array, you can use an additional reshape: 如果您想要它作为二维数组,您可以使用额外的重塑:
>>> A[range(len(I)),I].reshape(-1,1)
array([[0],
[3],
[4]])
A[:,[0,1,0]]
gives something completely different (what?)
给出了完全不同的东西(什么?)
It creates a matrix where the first column is the first ( 0
) column of A
, the second column is the second ( 1
) column of A
, and the third column is again the first ( 0
) column of A
. 它创建了一个矩阵,其中第一列是第一个(
0
的)柱A
, 第二列是第二( 1
)的列A
,以及第三列再次是第一个( 0
的)柱A
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.