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

Benjamin Root ben.root@ou....
Tue Aug 10 09:18:11 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.
>
> Therefore I wrote the following subfunction, but it is not very powerful:
>
> def ReduceArray(x,y):
>    x0=[]
>    j=0
>    for i in x:
>        j=j+1
>        if j==y:
>            x0.append(i)
>            j=0
>    return numpy.array(x0)
>
> Yes, using a simple Python list in between ... :-(((
>
> So if you had some hints on which way to follow to have this computed
> quickly,
> on a flat or a ndarray, you will make someone happy :-)
>
> Best regards,
> Matthieu
>
> PS : I apologize it this should have go to the numpy list, I was unsure...
>
> RapidEye AG
> Molkenmarkt 30
> 14776 Brandenburg an der Havel
> Germany
>
>
Would slicing the array help?

>>> a = numpy.array([0, 1, 2, 3, 4, 5])
>>> a[::2]   # every second element
array([0, 2, 4])

As a side benefit, you can save on memory because this 'slice' is actually a
view into the original array.

I hope that helps,

Ben Root
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20100810/72903693/attachment.html 


More information about the SciPy-User mailing list