[SciPy-User] Best method to pick-up every N-th sample of an array

Ryan May rmay31@gmail....
Tue Aug 10 09:15:33 CDT 2010


On Tue, Aug 10, 2010 at 9:11 AM, Matthieu Rigal <rigal@rapideye.de> wrote:
> Hi folks,
>
> I could not find an appropriate function to pick-up every N-th value of an
> array into another one... for example :
> [0,1,2,3,4,5] could return [0,2,4], for N = 2
> Neither I could find help browsing the dev-lists
>
> The functions numpy.choose and numpy.take may give correct results, but after
> having created the appropriate mask.. which may not be the best when you
> handle arrays containing hundred million of values, and I wouldn't be sure how
> to build it.

Python's slice notation supports it, with slices being noted as:

start:stop:step

If start is not given, it defaults to the start of the array (0). If
stop is not given, it defaults to the end. The following examples
should explain what I mean:

In [1]: a = np.arange(10)

In [2]: a
Out[2]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: a[::2]
Out[3]: array([0, 2, 4, 6, 8])

In [4]: a[::3]
Out[4]: array([0, 3, 6, 9])

In [5]: a[1::2]
Out[5]: array([1, 3, 5, 7, 9])

Ryan

-- 
Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma


More information about the SciPy-User mailing list