Reputation: 495
I want to select in an numpy array all odd off diagonals. Basically the following:
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]])
To formulate it differently: In each even row I want to have each second column with an offset of one and in each odd row I want to have each second column. It would be great if that could be achieved without creating an additional copy.
Upvotes: 2
Views: 3222
Reputation: 495
Okay if we can not avoid any copy, than the easiest thing to do would be probably something like:
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.]])
Upvotes: 4