简体   繁体   English

访问numpy数组中行特定元素的矢量化方法

[英]Vectorized way of accessing row specific elements in a numpy array

I have a 2-D NumPy array and a set of indices the size of which is the first dimension of the NumPy array. 我有一个二维NumPy数组和一组索引,其大小是NumPy数组的第一维。

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? 有矢量化的方法吗?

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. 我在这里假设您不需要在单独的行上每个值,而只想提取这些值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM