Python Forum

Full Version: How to sum elements of same position in n dimensional array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, guys,

I have a numpy array of (2,100,2) dimensions, that I want to sum elements of the same position. In order to clarify my doubts, I wrote the example below where I substituted the numbers by letters with dimensions (2,2,2): 

[[[a b]
  [c d]]
 [[a b]
  [c d]]]
So, I look for a way to sum a+a, b+b, c+c, d+d, and obtain an array with dimensions (2,2,1). Here's the desired output:

[[a+a  b+b]
 [c+c  d+d]]
I'd like something that I can extrapolate to cases with dimensions (2,100,X), where X can be numbers from 2 to 10.
Thanks !!!
It seems that you can use .sum() method with axis parameter.

In [1]: import numpy as np

In [2]: a = np.array([[[1,2], [3,4]], [[10, 20], [30, 40]]])

In [3]: a
Out[3]: 
array([[[ 1,  2],
        [ 3,  4]],
       [[10, 20],
        [30, 40]]])

In [4]: a.sum(axis=0)
Out[4]: 
array([[11, 22],
       [33, 44]])
As you can see, result has dimensionality reduced to (2, 2), if you want result with shape (2, 2, 1), you need to reshape it or add new dimension:
In [5]: a.sum(axis=0)[..., None]
Out[5]: 
array([[[11],
        [22]],
       [[33],
        [44]]])
(May-11-2017, 09:12 AM)zivoni Wrote: [ -> ]It seems that you can use .sum() method with axis parameter.

In [1]: import numpy as np

In [2]: a = np.array([[[1,2], [3,4]], [[10, 20], [30, 40]]])

In [3]: a
Out[3]: 
array([[[ 1,  2],
        [ 3,  4]],
       [[10, 20],
        [30, 40]]])

In [4]: a.sum(axis=0)
Out[4]: 
array([[11, 22],
       [33, 44]])
As you can see, result has dimensionality reduced to (2, 2), if you want result with shape (2, 2, 1), you need to reshape it or add new dimension:
In [5]: a.sum(axis=0)[..., None]
Out[5]: 
array([[[11],
        [22]],
       [[33],
        [44]]])
Thank you !!! This works perfectly for me.