How to select different columns from each row in nd-array in Python/numpy?

。_饼干妹妹 提交于 2019-12-23 13:26:35

问题


Suppose I have 3 x 2 matrix

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


回答1:


What you can do is pass an iterable of the first dimesion value, and an iterable (e.g. a list) of the second dimension. 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.



来源:https://stackoverflow.com/questions/46425782/how-to-select-different-columns-from-each-row-in-nd-array-in-python-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!