1

I want to numpy.sum() my nD arrays (matrix) of shape (2,2,2...n) to 1D arrays of shape (2,).

Basically along the axis=0. (Sum the first number of each 1d array of shape (2,) and sum the second number of the same arrays into one single resulting 1d array of shape (2,)).

However matrix.sum(axis=0) only seems to work for those of shape (2,2), while I think matrix.sum(axis=(1,2)) works for (2,2,2). But then what about (2,2,2,2) arrays and so on?

The n-dimensions have been confusing me. A generalised solution, along with a brief explanation, would be much appreciated.

EDIT: I've provided an example of the nD arrays I'm trying to sum below. I want to sum along axis=0 to get a (2,) 1D array. numpy.sum(axis=0) seems to only work for the array of shape (2,2)...

#Of shape (2,2):
[[9.99695358e-02 9.99232016e-01]
 [9.00030464e-01 7.67983971e-04]].sum(axis=0) seems to work

#Of shape (2,2,2):
[[[2.02737071e-01 7.75883149e-01]
  [2.02650032e-08 1.58192237e-02]]
 [[7.31718878e-06 1.41793363e-03]
  [4.12802168e-03 7.26350831e-06]]].sum(axis=(1,2)) seems to work

#Of shape… (2,2,2,2)
[[[[1.83819962e+00 1.02712560e-02]
   [5.05122135e-02 2.80555725e-04]]
  [[5.60304309e-07 5.44521143e-04]
   [2.41592380e-03 1.49436734e-05]]]
 [[[7.04398015e-05 7.66717944e-06]
   [1.76843337e-05 1.98868986e-06]]
  [[9.74010599e-02 1.12527543e-07]
   [2.61427056e-04 2.70778171e-08]]]].sum(axis=?) # What axis? And how to generalise?
2
  • What have you tried so far? I'd encourage you to add a minimal reproducible example illustrating what you've tried so far and to narrow this down to a specific question, otherwise this will likely keep getting downvotes and close votes. Commented Nov 21, 2019 at 17:53
  • 1
    Won't the answers to your previous question work if you simply replace multiplication * with addition +? Commented Nov 21, 2019 at 17:56

1 Answer 1

1

What do you think about reshaping x to 2D and summing along the second axis?

x.reshape(x.shape[0], -1).sum(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

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.