如果数组的长度是窗口大小的倍数 -
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])