9

I want to compute the integral image. for example

a=array([(1,2,3),(4,5,6)])
b = a.cumsum(axis=0)

This will generate another array b.Can I execute the cumsum in-place. If not . Are there any other methods to do that

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Samuel
  • 5,977
  • 14
  • 55
  • 77

2 Answers2

11

You have to pass the argument out:

np.cumsum(a, axis=1, out=a)

OBS: your array is actually a 2-D array, so you can use axis=0 to sum along the rows and axis=1 to sum along the columns.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
  • Is this the same to a=np.cumsum(a,axis=1). How can I confirm the `a` is the original one – Samuel Aug 28 '13 at 13:31
  • @Samuel [in the documentation it states](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) that this function returns a new array, but I don't know how to check if it is the same object, for other objects we could use `hash()`, but np.ndarrays are unhashable... – Saullo G. P. Castro Aug 28 '13 at 13:35
  • 1
    It can be confirmed by the address of `a.data`. I have confirmed that it's in-place in your way thanks – Samuel Aug 28 '13 at 13:37
  • @Samuel good to know this... I've been using `.data` in Cython but I never thought of using it for other purposes – Saullo G. P. Castro Aug 28 '13 at 13:38
  • 2
    @Samuel - Don't use `a.data` for this. It will only work in a very limited number of cases (e.g. what you're doing where the same array is returned, instead of a new array that shares the same data). Use `numpy.may_share_memory` instead. – Joe Kington Aug 28 '13 at 15:04
-3

Try this using numpy directly numpy.cumsum(a) :

a=array([(1,2,3)])
b = np.cumsum(a)
print b
>>array([1,3,6]) 
Dman2
  • 700
  • 4
  • 10