Sub topic 2
Reducing an array to a single value
This chapter assumes you can create arrays with np.array and np.arange, read an array's shape, and write basic Python. It covers the simplest form of aggregation, where a whole array collapses to one number. The next chapter adds the axis argument, which lets you reduce in a chosen direction instead.
What a reduction is
A reduction (also called an aggregation) takes many values and combines them into fewer values. With no extra arguments, NumPy combines every element of the array into one scalar, whatever the array's number of dimensions.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)
print(a.sum()) # 21
print(a.prod()) # 720
print(a.min(), a.max()) # 1 6
print(a.mean()) # 3.5
print(np.median(a)) # 3.5
print(a.var()) # 2.9166666666666665
print(round(a.std(), 4)) # 1.7078A 2×3 array has six elements. Each call above visits all six and returns one value. The array's shape does not matter when no axis is given. The same call on a.ravel(), which is the flattened 1-D version of a, gives the same answer.
Function form and method form
Most reductions can be written two ways. np.sum(a) and a.sum() do the same work, and so do np.max(a) and a.max(). Choose one style and use it consistently. The function form also accepts lists, because it converts them to arrays first.
import numpy as np
values = [3, 1, 4, 1, 5]
print(np.sum(values)) # 14
print(np.max(values)) # 5
# values.sum() would fail: a list has no sum methodSome reductions exist only as functions. np.median is one, and a.median() raises AttributeError. The same applies to np.average, which accepts weights, and to np.percentile.
The common reductions
| Function | What it returns | Result for an integer array | Empty array |
|---|---|---|---|
| `sum` | Total of all elements | Integer | `0` |
| `prod` | Product of all elements | Integer | `1` |
| `min`, `max` | Smallest, largest element | Same dtype as input | Raises `ValueError` |
| `mean` | Arithmetic average | `float64` | `nan` with a warning |
| `median` | Middle value of the sorted data | `float64` | `nan` with a warning |
| `var`, `std` | Spread around the mean | `float64` | `nan` with a warning |
| `any`, `all` | Whether some or all elements are truthy | `bool` | `False`, `True` |
| `count_nonzero` | Number of nonzero elements | Integer | `0` |
Two points in the table matter in practice.
sumandprodreturn the operation's identity value for an empty array. The identity of addition is 0 and of multiplication is 1.minandmaxhave no identity, so NumPy refuses to guess.meanalways returns a float, even for integers, because an average is rarely a whole number.
Why the identity matters
The identity explains an error you will meet when filtering data. If a filter removes every element, the following code fails:
import numpy as np
readings = np.array([12.5, 9.0, 14.2])
above_limit = readings[readings > 100] # empty array
print(above_limit.sum()) # 0.0
print(above_limit.max(initial=0.0)) # 0.0
try:
above_limit.max()
except ValueError as err:
print(err)
# zero-size array to reduction operation maximum which has no identityThe initial argument supplies a starting value for the comparison. For max it works as a floor. It turns the empty case into a defined answer, and the answer is 0.0 here because the floor is 0.0. If the data is not empty, initial also takes part in the comparison, so max(initial=0.0) on all-negative data returns 0.0, not the largest negative value. Pick a value that cannot distort real results, or check a.size before you reduce.
Standard deviation and the ddof argument
np.std and np.var divide by N, the number of elements, by default. That gives the population statistic. If your data is a sample and you want the sample statistic, pass ddof=1 so the divisor becomes N - 1. Pandas uses ddof=1 by default, so results from the two libraries differ unless you align them.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(round(np.std(a), 4)) # 1.7078 (divide by 6)
print(round(np.std(a, ddof=1), 4)) # 1.8708 (divide by 5)Reducing booleans
A boolean array is a convenient way to count things. True counts as 1 and False as 0 in arithmetic, so sum counts matches and mean gives the fraction of matches.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
big = a > 3
print(big.sum()) # 3
print(np.count_nonzero(big)) # 3
print(big.mean()) # 0.5
print(big.any(), big.all()) # True Falseany and all stop early when the answer is decided. This makes them cheap on large arrays where the first element already settles the result.
Data types of the result
Reductions do not always return the dtype you started with.
sumandprodon small integer types (int8,int16, and unsigned equivalents) accumulate in the platform's default integer, usually 64 bits. This avoids the overflow you might expect.minandmaxkeep the input dtype, because they only select existing elements.mean,median,std, andvarreturnfloat64for integer input.
import numpy as np
small = np.array([100, 100], dtype=np.int8)
total = small.sum()
print(total, total.dtype) # 200 int64 (int32 on 32-bit or older Windows builds)
print(small.max().dtype) # int8
print(small.mean().dtype) # float64Casting is not automatic in the other direction. If you add two int8 arrays with +, the result stays int8 and can wrap around. Reductions are safer than elementwise arithmetic here, but you can still overflow int64 with very large values. A later chapter covers overflow and the dtype argument.
Python's built-in functions are different
Python has its own sum, min, and max. They work on any iterable and know nothing about array dimensions. On a 2-D array they iterate over the rows.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(sum(a)) # [5 7 9] rows added together, not a scalar
print(np.sum(a)) # 21sum(a) returned an array of column totals. This happened by accident, because adding the row arrays is elementwise. max(a) is worse. It compares whole rows and raises ValueError: The truth value of an array with more than one element is ambiguous. The built-ins are also much slower on large arrays, since they loop in Python instead of in compiled code. Prefer np.sum, np.min, and np.max.
A related trap is the name np.max versus np.maximum. np.max(a) reduces one array to a scalar. np.maximum(a, b) compares two arrays elementwise and returns an array. They are different operations.
How a reduction works inside
Reductions are built on universal functions, or ufuncs. np.add is the ufunc that adds two arrays. Every ufunc has a reduce method that applies the operation repeatedly across an array. np.sum is essentially a convenient wrapper around np.add.reduce.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(np.add.reduce(a, axis=None)) # 21
print(np.multiply.reduce(a, axis=None)) # 720
print(np.maximum.reduce(a, axis=None)) # 6Here axis=None means all axes. Note that ufunc.reduce defaults to axis=0, unlike np.sum, so passing it explicitly is the safe habit. You rarely need reduce directly, but it explains why reductions share the same arguments (axis, dtype, keepdims, initial, where) and the same identity rules.
One consequence is that floating-point sums are not exact. NumPy adds floats in a particular order, using pairwise summation to limit rounding error, and the result can differ in the last digits from a Python loop over the same numbers. Do not compare float totals with ==. Use np.isclose or np.allclose.
Missing values spoil a total
If any element is nan, every plain reduction over the array returns nan, because nan propagates through arithmetic.
import numpy as np
c = np.array([1.0, np.nan, 3.0])
print(c.sum()) # nan
print(np.nansum(c)) # 4.0The nan-prefixed functions skip missing values. They get a full treatment in a later chapter.
Common mistakes
- Using the built-in
sum,min, ormaxon a 2-D array and getting an array or an error instead of a scalar. - Calling
a.median(). Usenp.median(a). - Reducing an empty array with
minormaxwithout checkinga.sizeor passinginitial. - Assuming
np.stdis the sample standard deviation. It divides byNunless you passddof=1. - Comparing float results with
==instead ofnp.isclose. - Forgetting that
nanpoisonssum,mean,min, andmax.
Exercise
The array scores = np.array([[70, 85], [90, 60], [75, 80]]) holds exam marks. Write one expression for the fraction of marks that are at least 75, then say what scores.mean() and np.median(scores) return.
Show answer
(scores >= 75).mean() returns 0.5, because three of the six marks (85, 90, 80... counting 85, 90, 75, 80) are at least 75. Counting carefully, the marks 85, 90, 75 and 80 all qualify, so four of six qualify and the fraction is 4/6, about 0.6667. scores.mean() is the total 460 divided by 6, which is about 76.6667. For np.median(scores), the sorted values are 60, 70, 75, 80, 85, 90, and the median is the average of the middle two, (75 + 80) / 2 = 77.5.
Exercise
Why does np.array([], dtype=float).sum() return 0.0 while np.array([], dtype=float).max() raises an error?
Show answer
Addition has an identity value, 0, so the sum of nothing is well defined. Maximum has no identity, so NumPy cannot return a meaningful answer for an empty array. Pass initial= to max, or check a.size first.