Python Forum
How to sum elements of same position in n dimensional array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: How to sum elements of same position in n dimensional array (/thread-3280.html)



How to sum elements of same position in n dimensional array - Felipe - May-11-2017

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 !!!


RE: How to sum elements of same position in n dimensional array - zivoni - May-11-2017

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]]])



RE: How to sum elements of same position in n dimensional array - Felipe - May-11-2017

(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.