在NumPy中的索引:访问每个其他组的值

3
[::n] 是numpy中的索引选项,可以提供一种非常有用的方式来索引列表中每个第n个项目。但是,是否可以使用此功能提取多个值,例如每两个的值?
例如:
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

我希望提取每隔一对值,即我想返回

a[0, 1, 4, 5, 8, 9,]

当然可以使用循环或其他方法构建索引,但我想知道是否有更快的方法在 numpy 中使用 :: 形式的索引,并指定每 nth 迭代要取的模式的宽度。
谢谢。
2个回答

7

如果数组的长度是窗口大小的倍数 -

In [29]: W = 2 # window-size

In [30]: a.reshape(-1,W)[::2].ravel()
Out[30]: array([0, 1, 4, 5, 8, 9])

按照步骤解释 -

# Reshape to split into W-sized groups
In [43]: a.reshape(-1,W)
Out[43]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

# Use stepsize to select every other pair starting from the first one
In [44]: a.reshape(-1,W)[::2]
Out[44]: 
array([[0, 1],
       [4, 5],
       [8, 9]])

# Flatten for desired output
In [45]: a.reshape(-1,W)[::2].ravel()
Out[45]: array([0, 1, 4, 5, 8, 9])

如果你可以接受 2D 的输出结果,那么可以跳过最后一步,因为它仍然是对输入的一种视图,并且几乎不需要运行时成本。让我们验证这个视图部分-

In [47]: np.shares_memory(a,a.reshape(-1,W)[::2])
Out[47]: True

对于不一定是倍数的一般情况,我们可以使用基于 掩码 的方法 -

In [64]: a[(np.arange(len(a))%(2*W))<W]
Out[64]: array([0, 1, 4, 5, 8, 9])

0

你可以将数组重塑为一个nx3矩阵,然后对每一行切片前两个元素,最后展平重塑后的数组:

a.reshape((-1,3))[:,:2].flatten()

导致:
array([ 0,  1,  3,  4,  6,  7,  9, 10])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接