Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have an ndarray with 100 elements, and I want to select the first 4 elements, skip 6 and go ahead like this (in other words, select the first 4 elements every 10 elements).

I tried with python slicing with step but I think it's not working in my case. How can I do that? I'm using Pandas and numpy, can they help? I searched around but I have found nothing like that kind of slicing. Thanks!

like image 574
giglio91 Avatar asked Nov 19 '15 10:11

giglio91


2 Answers

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])
like image 173
Divakar Avatar answered Oct 10 '22 00:10

Divakar


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]
like image 32
tmdavison Avatar answered Oct 10 '22 02:10

tmdavison