Module 4 · Lesson 1

Aggregations & the axis Parameter

np.sum, np.mean, np.std, np.min, np.max all reduce an array to fewer numbers. Called with no axis, they collapse the whole array to a single scalar. With axis=0 they reduce along rows — one result per column. With axis=1 they reduce along columns — one result per row.

CallMeaning
arr.sum()one total, whole array
arr.sum(axis=0)one total per column (walks down each column)
arr.sum(axis=1)one total per row (walks across each row)

Pass keepdims=True to keep the reduced axis as length-1 instead of dropping it — handy when you want the result to broadcast back against the original array.

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

print("whole array sum:", grid.sum())
print("column sums (axis=0):", grid.sum(axis=0))
print("row sums (axis=1):   ", grid.sum(axis=1))
print("row means, keepdims: ", grid.mean(axis=1, keepdims=True).ravel())

# keepdims=True lets you broadcast the result back against the original:
centered = grid - grid.mean(axis=1, keepdims=True)
print(centered)

Output:

whole array sum: 21
column sums (axis=0): [5 7 9]
row sums (axis=1):    [ 6 15]
row means, keepdims:  [2. 5.]
[[-1.  0.  1.]
 [-1.  0.  1.]]
1.1

Column-normalize a matrix

Write normalize_columns(grid) that returns a copy of grid where each column has been divided by that column's sum, so every column sums to 1.0. grid is a 2-D array of positive floats.

💡 Hint

Divide grid by grid.sum(axis=0) — broadcasting lines up a length-n_cols array against each row automatically.

✅ Solution
def normalize_columns(grid):
    return grid / grid.sum(axis=0)
1.2

Row-wise range

Write row_ranges(grid) that returns a 1-D array with, for each row, the difference between that row's max and min value (max - min).

💡 Hint

grid.max(axis=1) - grid.min(axis=1).

✅ Solution
def row_ranges(grid):
    return grid.max(axis=1) - grid.min(axis=1)