Sub topic 2
Reducing an array to a single value
This chapter assumes you can create arrays with np.array and np.arange, and that you know what an array's shape means. It covers what a reduction is and how the basic reductions behave when you call them with no axis.
What a reduction does
An aggregation, also called a reduction, takes many values and combines them into fewer values. sum adds the values. max keeps the largest. mean adds them and divides by the count. With no axis argument, NumPy reduces the whole array to one scalar, no matter how many dimensions it has.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.shape) # (2, 3)
print(a.sum()) # 21
print(a.max()) # 6
print(a.min()) # 1
print(a.mean()) # 3.5
print(a.size) # 6The result of each call is a single number, not an array. The 2×3 shape disappears because every element took part in the reduction.
Two ways to call the same function
Most reductions exist both as an array method and as a function in the np namespace. They give the same result.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum()) # 21
print(np.sum(a)) # 21
print(np.mean(a)) # 3.5
print(a.mean()) # 3.5Use whichever style fits the code around it. The function form also accepts plain Python lists, such as np.sum([1, 2, 3]), and converts them first.
Avoid the built-in sum(a) on a 2D array. Python's sum iterates over the first axis and adds whole rows together, so it returns an array instead of a scalar. It is also much slower than the NumPy version.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(sum(a)) # [5 7 9]
print(np.sum(a)) # 21Common reductions
| Function | Result for `[[1, 2, 3], [4, 5, 6]]` | Meaning |
|---|---|---|
| `sum` | 21 | Total of all elements |
| `prod` | 720 | Product of all elements |
| `min` | 1 | Smallest element |
| `max` | 6 | Largest element |
| `mean` | 3.5 | Arithmetic average |
| `std` | about 1.71 | Standard deviation |
| `any` | True | True if any element is truthy |
| `all` | True | True if every element is truthy |
any and all are reductions too. They turn an array into a single Boolean, which is useful with comparisons such as (a > 0).all().
Why the whole-array default is only a start
Reducing everything is often too coarse. Suppose each row is a student and each column is a test. One grand total tells you little. You usually want one total per student or one total per test. The axis argument gives you that control, and the next chapters build on it.
Things to check
- The result of a no-axis reduction is a NumPy scalar such as
np.int64, not a one-element array. Itsshapeis(). meanalways returns a floating-point number, even for integer input.- An empty array gives
0forsumand1forprod.maxandminon an empty array raise aValueError, because there is no sensible answer.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
total = a.sum()
print(type(total)) # <class 'numpy.int64'>
print(total.shape) # ()
print(a.mean().dtype) # float64
print(np.array([]).sum()) # 0.0On Windows, or with older NumPy versions, the default integer type may print as int32 instead. The behavior is the same.
Exercise
For a = np.array([[2, 4], [6, 8]]), what do a.sum(), a.max(), and a.mean() return, and what is the shape of each result?
Show answer
a.sum() is 20, a.max() is 8, and a.mean() is 5.0. Each result is a scalar, so its shape is ().
Exercise
A colleague writes sum(a) on a 2D array and gets an array back instead of one number. Why, and what should they use?
Show answer
Python's built-in sum loops over the first axis and adds the rows together, so the result is an array of column totals. Using a.sum() or np.sum(a) reduces the whole array to a single scalar.