Numpy 索引,获取宽度为 2 的条带

Numpy index, get bands of width 2

我想知道是否有办法 index/slice 一个 numpy 数组,这样就可以得到 2 个元素的每隔一个带。换句话说,给定:

test = np.array([[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]])

我要获取数组:

[[1,  2,  5,  6],
 [9, 10, 13, 14]]

关于如何使用 slicing/indexing 实现这一点的想法?

通过一些巧妙的整形并不难:)

test.reshape((4, 4))[:, :2].reshape((2, 4))

鉴于:

>>> test
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16]])

你可以这样做:

>>> test.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1,  2,  5,  6],
       [ 9, 10, 13, 14]])

这甚至适用于不同形状的初始数组:

>>> test2
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])
>>> test2.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1,  2,  5,  6],
       [ 9, 10, 13, 14]])

>>> test3
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])
>>> test3.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1,  2,  5,  6],
       [ 9, 10, 13, 14]])

工作原理:

1. Reshape into two columns by however many rows:
>>> test.reshape(-1,2)
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10],
       [11, 12],
       [13, 14],
       [15, 16]])

2. Stride the array by stepping every second element
>>> test.reshape(-1,2)[::2]
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10],
       [13, 14]])

3. Set the shape you want of 4 columns, however many rows:
>>> test.reshape(-1,2)[::2].reshape(-1,4)
array([[ 1,  2,  5,  6],
       [ 9, 10, 13, 14]])