0

Say I have a numpy 2D array:

>>> t
array([[-0.00880717,  0.02522217, -0.01014062],
       [-0.00866732,  0.01737254,  0.05396272]])

Now using array slicing, I can quickly obtain all items in all rows starting from the column with index 1 and sum them up:

>>> t[:, 1:].sum()
0.08641680780899146

To verify manually, here is what happens:

>>> 0.02522217+0.01737254+-0.01014062+0.05396272
0.08641680999999998

Just to understand the numpy array operations better, is numpy first going over all rows and summing the items of the rows, or is it going down one column, and then down the next one?

1
  • 1
    Since you don't specify an axis, the sum is over the flattened view. The row versus column distiction does not apply. Your values match for 8 decimals, to 80. Commented May 1, 2021 at 18:24

1 Answer 1

2

Thanks for asking your question, @TMOTTM!

The way NumPy's sum semantics work are documented in the NumPy manual.

To summarize the manual while injecting my own understanding:

  1. arr.sum() called without an axis argument simply sums up everything in the array. It is the most straightforward semantic operation to implement.
  2. arr.sum(axis=0) will collapse axis 0 (the first axis) while summing.
  3. arr.sum(axis=k) will collapse axis k while performing a summation.

Canonically, axis 0 is semantically recognized as the row-wise axis, axis 1 is the column-wise axis, and axis 2 is the depth-wise axis, and anything higher goes into hypercubes which are not easily described in words.

Made concrete:

  1. In a 2D array, to collapse the rows (i.e. sum column-wise), do arr.sum(axis=0).
  2. In a 2D array, to collapse the columns (i.e. sum row-wise), do arr.sum(axis=1).

At the end of the day, point 3 is the one you want to remember: reason carefully about which axis you wish to collapse, and you'll never go wrong!

Sign up to request clarification or add additional context in comments.

2 Comments

He doesn't specify axis, so point 1) applies. I suspect he's bothered by the value difference beyond the 8th decimal.
Thank you for your comment, no not at all. I was not aware of the axis concept playing in also when absent

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.