[Numpy-discussion] partial_sum/adj_difference?

Francesc Altet faltet@carabos....
Tue Feb 19 12:59:48 CST 2008


A Tuesday 19 February 2008, Neal Becker escrigué:
> Does numpy/scipy have a partial_sum and adj_difference function?
>
> partial_sum[i] = \sum_{j=0}^{i} x[j]
> adj_diff[i] = x[i] - x[i-1] : i > 1, x[i] otherwise

I don't know, but by using views the next should be fairly efficient:

# Partial sum
In [28]: a = numpy.arange(10)
In [29]: ps = numpy.empty(len(a), 'int')
In [30]: for i in range(len(a)): ps[i] = a[:i].sum()
   ....:
In [31]: ps
Out[31]: array([ 0,  0,  1,  3,  6, 10, 15, 21, 28, 36])

# Adj difference:
In [35]: ad = numpy.empty(len(a), 'int')
In [36]: ad[0] = a[0]
In [37]: ad[1:] = a[1:] - a[:-1]
In [38]: ad
Out[38]: array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1])

Cheers,

-- 
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 "-"


More information about the Numpy-discussion mailing list