How can I select n items and skip m from ndarray in python?

Solution 1:

You could use NumPy slicing to solve your case.

For a 1D array case -

A.reshape(-1,10)[:,:4].reshape(-1)

This can be extended to a 2D array case with the selection to be made along the first axis -

A.reshape(-1,10,A.shape[1])[:,:4].reshape(-1,A.shape[1])

Solution 2:

You could reshape the array to a 10x10, then use slicing to pick the first 4 elements of each row. Then flatten the reshaped, sliced array:

In [46]: print a
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]

In [47]: print a.reshape((10,-1))[:,:4].flatten()
[ 0  1  2  3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 50 51 52 53 60
 61 62 63 70 71 72 73 80 81 82 83 90 91 92 93]

Solution 3:

Use % 10:

print [i for i in range(100) if i % 10 in (0, 1, 2, 3)]

[0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, 40, 41, 42, 43, 50, 51, 52, 53, 60, 61, 62, 63, 70, 71, 72, 73, 80, 81, 82, 83, 90, 91, 92, 93]