Vectorized way of accessing row specific elements in a numpy array

為{幸葍}努か 提交于 2019-12-24 13:05:46

问题


I have a 2-D NumPy array and a set of indices the size of which is the first dimension of the NumPy array.

X = np.random.rand(5, 3)
a = np.random.randint(0, 3, 5)

I need to do something like

for i, ind in enumerate(a):
    print X[i][ind]

Is there a vectorized way of doing this?


回答1:


Here you go:

X = np.random.rand(5, 3)
a = np.random.randint(0, 3, 5)

In [12]: X[np.arange(a.size), a]
Out[12]: array([ 0.99653335,  0.30275346,  0.92844957,  0.54728781,  0.43535668])
In [13]: for i, ind in enumerate(a):
            print X[i][ind]
#   ....:
#0.996533345844
#0.30275345582
#0.92844956619
#0.54728781105
#0.435356681672

I'm assuming here that you don't need each value on a separate line and just want to extract the values.



来源:https://stackoverflow.com/questions/25650066/vectorized-way-of-accessing-row-specific-elements-in-a-numpy-array

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