Numpy 索引:获取每一偶数行的每隔一列

Numpy Indexing: Get every second coloumn for each even row

我想 select 在一个 numpy 数组中所有奇数对角线。基本上如下:

a = np.arange(16).reshape(4,4)
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
b = a[::2,1::2] and at the same time a[1::2,::2]
array([[ 1,  3],
       [ 4, 6],
       [9, 11],
       [12,14]])

以不同的方式表述:在每个偶数行中,我希望每个第二列的偏移量为 1,在每个奇数行中,我希望每个第二列。如果可以在不创建额外副本的情况下实现这一点,那就太好了。

好吧,如果我们无法避免任何复制,那么最简单的事情可能是这样的:

a = np.arange(16).reshape(4,4)
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
b = np.zeros((a.shape[0], a.shape[1]/2))
b[::2,:]  = a[::2,1::2]
b[1::2,:] = a[1::2,::2]
>>>> b
array([[  1.,   3.],
   [  4.,   6.],
   [  9.,  11.],
   [ 12.,  14.]])