6

How do I use the numpy accumulator and add functions to add arrays column wise to make a basic accumulator?

   import numpy as np
   a = np.array([1,1,1])
   b = np.array([2,2,2])
   c = np.array([3,3,3])
   two_dim = np.array([a,b,c])
   y = np.array([0,0,0])
   for x in two_dim:
     y = np.add.accumulate(x,axis=0,out=y)                               
     return y

actual output: [1,2,3] desired output: [6,6,6]

numpy glossary says the sum along axis argument axis=1 sums over rows: "we can sum each row of an array, in which case we operate along columns, or axis 1".

"A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1)"

With axis=1 I would expect output [3,6,9], but this also returns [1,2,3].

Of Course! neither x nor y are two-dimensional.

What am I doing wrong?

I can manually use np.add()

aa = np.array([1,1,1])
bb = np.array([2,2,2])
cc = np.array([3,3,3])
yy = np.array([0,0,0])
l = np.add(aa,yy)
m = np.add(bb,l)
n = np.add(cc,m)
print n

and now I get the correct output, [6,6,6]

1 Answer 1

5

I think

two_dim.sum(axis=0)
# [6 6 6]

will give you what you want.

I don't think accumulate is what you're looking for as it provides a running operation, so, using add it would look like:

np.add.accumulate(two_dim)

[[1 1 1]
 [3 3 3]    # = 1+2
 [6 6 6]]   # = 1+2+3

reduce is more like what you've descibed:

np.add.reduce(two_dim)

[6 6 6]
Sign up to request clarification or add additional context in comments.

3 Comments

LOL. Reading example with np.accumulate I thought a numpy func would be the way to go. I'm humbled.
Actually, I would like to have the running total in the array. I will try to read the docs to see which is best. tx.
@xtian: Just to be clear, sum as used here is the numpy version and not the python version. If you want the running totals, you could use add.accumulate or the cumulative sum cumsum, they're equivalent (at least in output).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.