xtian
xtian

Reputation: 2947

How to accumulate values in numpy array by column?

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]

Upvotes: 6

Views: 8571

Answers (1)

tom10
tom10

Reputation: 69242

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]

Upvotes: 5

Related Questions