TExcelTAD
Home › NumPy › ufunc Summations

ufunc Summations

There's a difference between addition and summation:

  • Addition (np.add(a, b)) combines two arrays element by element: the result has the same shape.
  • Summation (np.sum(a)) adds up the elements of an array: the result is smaller (a single number, or one number per row/column).
python · try it yourself
import numpy as np

week1 = np.array([5, 3, 8])
week2 = np.array([2, 7, 4])
print(np.add(week1, week2))          # element-wise: 3 numbers
print(np.sum([week1, week2]))        # everything summed: 1 number
[ 7 10 12]
29

Summing over an axis

With axis, you choose the direction. For a 2-D table, axis=0 collapses the rows (giving one total per column), and axis=1 collapses the columns (one total per row):

python · try it yourself
import numpy as np

# Rows: three shops. Columns: Mon..Fri sales
sales = np.array([[12, 15,  9, 20, 18],
                  [ 8, 11, 14, 10, 13],
                  [21, 19, 25, 23, 30]])

print("total:          ", sales.sum())
print("per day (axis 0):", sales.sum(axis=0))
print("per shop (axis 1):", sales.sum(axis=1))
print("keepdims shape: ", sales.sum(axis=1, keepdims=True).shape)
total:           248
per day (axis 0): [41 45 48 53 61]
per shop (axis 1): [ 74  56 118]
keepdims shape:  (3, 1)

A good way to remember it: the axis you pass is the one that disappears. keepdims=True keeps it with length 1, which is handy for dividing each row by its own total (see the Broadcasting lesson).

Cumulative sum

A cumulative sum (running total) adds the elements one at a time and keeps every partial result. np.cumsum([1, 2, 3]) is [1, 3, 6].

python · try it yourself
import numpy as np

deposits = np.array([100, -40, 250, -80, 60])
balance = np.cumsum(deposits)
print(balance)
print("lowest balance:", balance.min(), "after transaction", balance.argmin() + 1)

steps = np.array([[1, 2, 3],
                  [4, 5, 6]])
print(np.cumsum(steps, axis=1))      # running total along each row
[100  60 310 230 290]
lowest balance: 60 after transaction 2
[[ 1  3  6]
 [ 4  9 15]]

np.add.accumulate(a) is the ufunc-method way of writing np.cumsum(a), and np.add.reduce(a) is the same as np.sum(a).

Summing booleans and with conditions

Because True counts as 1, summing a boolean mask counts matches. np.sum also accepts where= to include only some elements:

python · try it yourself
import numpy as np

steps = np.array([4200, 10500, 8000, 12100, 3000, 9900, 11000])
print("days over 10k:", np.sum(steps > 10_000))
print("steps on those days:", np.sum(steps, where=steps > 10_000))
print("weekend total:", steps[-2:].sum())
days over 10k: 3
steps on those days: 33600
weekend total: 20900

Floating-point sums

Summing many floats accumulates rounding error, because 0.1 and most other decimals are not exact in binary. A naive running total drifts; NumPy's sum uses pairwise summation, which keeps the error much smaller; and Python's math.fsum returns the correctly rounded result:

python · try it yourself
import numpy as np
import math

values = np.full(10, 0.1)
total = 0.0
for v in values.tolist():         # naive running total
    total += v
print(total)
print(values.sum())               # NumPy
print(math.fsum(values))          # exact rounding
0.9999999999999999
1.0
1.0

Test yourself

For a 2-D array a with shape (3, 4), what is the shape of a.sum(axis=0)?

  1. (3,)
  2. (4,)
  3. (3, 4)
  4. ()

What is np.cumsum([2, 2, 2, 2])?

  1. 8
  2. [2 2 2 2]
  3. [2 4 6 8]
  4. [8 6 4 2]

What is the difference between np.add(a, b) and np.sum([a, b])?

  1. None
  2. add is element-wise; sum adds up all elements into one number
  3. sum is element-wise; add totals everything
  4. add only works with scalars