NumPy ufunc Summations

NumPy separates the idea of combining two arrays element-wise from summing the values inside a single array, and cumsum lets you follow the running total as it builds.

Sum vs Add: Two Different Operations

np.add(a, b) is a binary ufunc: it takes two arrays (or broadcastable shapes) and combines them element-by-element into a new array of the same shape. np.sum(a) is a reduction: it takes one array and collapses it down into a single total.

Example

import numpy as np

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])

# add() combines two arrays element-wise, returning an array of the same shape
added = np.add(a, b)
print(added)
# [11 22 33]

# sum() reduces a single array down to one total value
total = np.sum(a)
print(total)
# 6

Summing Along Axes

For multi-dimensional arrays, the axis parameter controls which direction sum() collapses. axis=0 sums down each column, axis=1 sums across each row, and omitting axis sums every element in the flattened array.

Example

import numpy as np

matrix = np.array([[1, 2, 3],
                    [4, 5, 6]])

print(np.sum(matrix))          # 21, sums every element
print(np.sum(matrix, axis=0))  # [5 7 9], sums down each column
print(np.sum(matrix, axis=1))  # [ 6 15], sums across each row

Cumulative Sums with cumsum()

np.cumsum() is also a reduction, but instead of returning only the final total, it returns an array of the same length holding every intermediate running total — useful for tracking a balance, a distance traveled, or a cumulative score over time.

Example

import numpy as np

daily_sales = np.array([120, 85, 200, 60, 150])

running_total = np.cumsum(daily_sales)
print(running_total)
# [120 205 405 465 615]

matrix = np.array([[1, 2, 3],
                    [4, 5, 6]])
print(np.cumsum(matrix, axis=1))
# [[ 1  3  6]
#  [ 4  9 15]]
  • np.add(a, b) is an element-wise ufunc; it requires (or broadcasts to) matching shapes and returns an array the same size as its inputs.
  • np.sum(a) is a reduction; it collapses an array, or one axis of it, into fewer values.
  • np.cumsum(a) is a reduction-like ufunc too, but it keeps every intermediate result instead of only the final total.
  • The axis parameter controls which dimension sum() and cumsum() collapse or accumulate along; omitting it operates on the flattened array.
FunctionOperation TypeOutput Shape
np.add(a, b)Element-wise (binary ufunc)Same shape as inputs
np.sum(a)ReductionScalar, or reduced along one axis
np.cumsum(a)Accumulating reductionSame size as input, holding running totals
Note: np.add(a, b) produces exactly the same result as writing a + b — the operator is just shorthand for calling the ufunc directly.

Exercise: NumPy ufunc Summations

What is the key difference between np.sum() and np.cumsum()?