Sub topic 4
Column totals and row totals
This chapter covers how the axis argument of sum picks between column totals and row totals, and how to predict the shape of the result. It assumes you know basic Python syntax, can build arrays with np.array and np.arange, and know that shape is a tuple with one length per dimension.
The two directions of a 2D array
A two-dimensional array has two axes. Axis 0 runs down the rows, so moving along axis 0 means going from one row to the next. Axis 1 runs across the columns, so moving along axis 1 means going from one column to the next. For an array of shape (3, 4), axis 0 has length 3 and axis 1 has length 4.
When you pass axis=k to a reduction such as sum, NumPy collapses that axis. For every position along the other axes, it combines all the values that lie along axis k.
axis=0combines the rows. The result has one value per column, so these are column totals.axis=1combines the columns. The result has one value per row, so these are row totals.
The axis you name is the one that disappears from the shape. The axis you do not name is the one that survives.
import numpy as np
sales = np.array([[120, 80, 95, 110],
[130, 70, 100, 90],
[150, 60, 105, 125]])
print(sales.shape) # (3, 4)
print(sales.sum()) # 1235
print(sales.sum(axis=0)) # [400 210 300 325]
print(sales.sum(axis=1)) # [405 390 440]Read sales as three days (rows) by four products (columns). With axis=0 the three days collapse, so you get one total per product. With axis=1 the four products collapse, so you get one total per day. With no axis, every value is combined into a single number.
What a total actually computes
Each entry of the result equals a sum over one slice of the array. A column is sales[:, j] and a row is sales[i, :]. You can check the result by slicing:
import numpy as np
sales = np.array([[120, 80, 95, 110],
[130, 70, 100, 90],
[150, 60, 105, 125]])
print(sales[:, 0].sum()) # 400, first entry of sales.sum(axis=0)
print(sales[1, :].sum()) # 390, second entry of sales.sum(axis=1)
col_totals = sales.sum(axis=0)
row_totals = sales.sum(axis=1)
assert col_totals.sum() == row_totals.sum() == sales.sum()The final assert is a useful sanity check. Both sets of totals add up to the grand total, because each one splits the same numbers into groups in a different way.
Predicting the result shape
The result shape is the input shape with the reduced axis removed. This lets you work out the shape before you run anything.
| Input shape | Call | Result shape |
|---|---|---|
| `(3, 4)` | `a.sum(axis=0)` | `(4,)` |
| `(3, 4)` | `a.sum(axis=1)` | `(3,)` |
| `(3, 4)` | `a.sum()` | `()`, a scalar |
| `(5,)` | `a.sum(axis=0)` | `()`, a scalar |
A one-dimensional array has only axis 0. Summing along it collapses the whole array to a scalar:
import numpy as np
v = np.array([3, 1, 2])
print(v.shape) # (3,)
print(v.sum(axis=0)) # 6The result of a column or row total is a one-dimensional array. A row total is not a column vector, even though you may picture it as one. This matters when you combine the result with the original array, which the next chapter covers.
Equivalent spellings
The method form and the function form give the same result, so sales.sum(axis=0) and np.sum(sales, axis=0) are interchangeable. Other reductions follow the same rule, so you can reuse what you learned for sum.
import numpy as np
sales = np.array([[120, 80, 95, 110],
[130, 70, 100, 90],
[150, 60, 105, 125]])
print(np.sum(sales, axis=0)) # [400 210 300 325]
print(sales.max(axis=0)) # [150 80 105 125]
print(sales.min(axis=1)) # [ 80 70 60]sales.max(axis=0) gives the best sales figure for each product across all days. sales.min(axis=1) gives the weakest product figure on each day.
Negative axes
Axes can be counted from the end. In a 2D array, axis=-1 is the same as axis=1, and axis=-2 is the same as axis=0. Using -1 for "the last axis" is common in code that must work on arrays with any number of dimensions, because the last axis stays the last axis however many leading dimensions you add.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a.sum(axis=-1)) # [ 6 15]
print(a.sum(axis=-2)) # [5 7 9]Putting totals back into a table
A common task is adding a totals row or a totals column to a table. np.vstack stacks arrays vertically, and np.column_stack places 1D arrays side by side as columns.
import numpy as np
sales = np.array([[120, 80, 95, 110],
[130, 70, 100, 90],
[150, 60, 105, 125]])
with_total_row = np.vstack([sales, sales.sum(axis=0)])
with_total_col = np.column_stack([sales, sales.sum(axis=1)])
print(with_total_row)
# [[120 80 95 110]
# [130 70 100 90]
# [150 60 105 125]
# [400 210 300 325]]
print(with_total_col)
# [[120 80 95 110 405]
# [130 70 100 90 390]
# [150 60 105 125 440]]The column totals have shape (4,), which matches the four columns, so they work as a new row. The row totals have shape (3,), which matches the three rows, so column_stack can use them as a new column. vstack would reject the row totals here because their length does not match the number of columns.
Common errors with row and column totals
Mixing up which axis to name
Many learners read axis=0 as "sum the rows" and expect one total per row. NumPy's behavior is the opposite: axis=0 collapses the rows and leaves one value per column.
Using an axis that does not exist
An axis number must be smaller than the number of dimensions. A 2D array has axes 0 and 1 only, so asking for axis 2 raises an error.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
try:
a.sum(axis=2)
except Exception as err:
print(type(err).__name__) # AxisError
print(err) # axis 2 is out of bounds for array of dimension 2This error often appears when an array has fewer dimensions than you thought, for example after a previous reduction. Print a.shape or a.ndim before you choose the axis.
Square arrays hide mistakes
On a square array such as (3, 3), both axis=0 and axis=1 return a shape of (3,). A wrong axis then produces plausible numbers with no error. Test your code on a non-square array, such as (2, 3) or (3, 4), so that a mistake shows up as a wrong length.
Expecting a 2D result
A reduction returns an array with one fewer dimension. If you pass sales.sum(axis=1) to code that expects a column of shape (3, 1), you will get a shape error or a silent broadcast against the wrong axis. The keepdims option, covered in the next chapter, keeps the reduced axis with length 1 for these cases.
Checking your work
Three habits catch most axis mistakes:
- Write down the shape before you call the reduction, then write down the shape you expect after it.
- Print
result.shapeand compare it to your expectation. - Verify one entry by hand with a slice, such as
a[:, 0].sum()for the first column total.
Exercise
An array m has shape (4, 5). What are the shapes of m.sum(axis=0) and m.sum(axis=1), and which one gives a total for each row?
Show answer
m.sum(axis=0) has shape (5,) because the 4 rows collapse, leaving one total per column. m.sum(axis=1) has shape (4,) because the 5 columns collapse, leaving one total per row. So axis=1 gives a total for each row.
Exercise
Let m = np.arange(12).reshape(3, 4). Without running the code, give the values of m.sum(axis=0) and m.sum(axis=1).
Show answer
The rows are [0, 1, 2, 3], [4, 5, 6, 7], and [8, 9, 10, 11]. Column totals (axis=0) are [12, 15, 18, 21]. Row totals (axis=1) are [6, 22, 38]. Both add up to 66, the value of m.sum().