Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stack summing vectors to numpy 3d array?

I have a 3d numpy array that looks like so:

>>> g
array([[[ 1.,  1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 1.,  2.,  3.,  4.,  6.]],

       [[ 0.,  0.,  0.,  0.,  0.],
        [11., 22., 33., 44., 66.],
        [ 0.,  0.,  0.,  0.,  0.]]])
  1. I know I can calculate a sum along the first axis with gs = g.sum(axis=1) that will result in this array:
>>> gs
array([[ 2.,  3.,  4.,  5.,  7.],
       [11., 22., 33., 44., 66.]])

How do I stack this summing array to the original one as the forth vector in each of the two inside groups? The expected result would be:

>>> g
array([[[ 1.,  1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 1.,  2.,  3.,  4.,  6.],
        [ 2.,  3.,  4.,  5.,  7.]],

       [[ 0.,  0.,  0.,  0.,  0.],
        [11., 22., 33., 44., 66.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 11., 22., 33., 44., 66.]]])
  1. And I have the same question about the summing array along the 0th dimension which is calculated with gss = g.sum(axis=0) and looks like so:
>>> gss
array([[ 1.,  1.,  1.,  1.,  1.],
       [11., 22., 33., 44., 66.],
       [ 1.,  2.,  3.,  4.,  6.]])

How do I stack it to the original array to get the result shown below?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> g
array([[[ 1.,  1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.,  0.],
        [ 1.,  2.,  3.,  4.,  6.]],

       [[ 0.,  0.,  0.,  0.,  0.],
        [11., 22., 33., 44., 66.],
        [ 0.,  0.,  0.,  0.,  0.]],

       [[ 1.,  1.,  1.,  1.,  1.],
        [11., 22., 33., 44., 66.],
        [ 1.,  2.,  3.,  4.,  6.]]])

>Solution :

np.concatenate([g, g.sum(axis=1, keepdims=True)], axis=1)

Equivalent for axis=0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading