Index numbers, get stripes 2 wide

I am wondering if there is a way to index / slice a numpy array so that I can get any other strip of 2 elements. In other words, given:

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

I would like to get an array:

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

Thoughts on how to do this with slicing / indexing?

+4
source share
2 answers

Not so complicated with a few smart changes :)

 test.reshape((4, 4))[:, :2].reshape((2, 4)) 
+3
source

Given:

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

You can do:

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

What works even for different forms of source arrays:

 >>> 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]]) 

How it works:

 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]]) 
+2
source

All Articles