Python · Module 7
Answers and explanations · NumPy arrays
Compare these references after your own attempt. You can read them at any time; they do not record a live model or vendor run.
Module 7
axis=1 reduces each row to one day total; axis=0 reduces rows to one total per column. A mask selects matching elements, and a high threshold produces an empty one-dimensional result. copy isolates the edit.
# Reference answer. Attempt the exercise first.
import numpy as np
values = np.array([[10., 40.], [20., 50.]])
row_totals = values.sum(axis=1)
column_totals = values.sum(axis=0)
selected = values[values >= 40]
first = values[0].copy()
first[0] = 99
assert np.array_equal(row_totals, [50, 70])
assert np.array_equal(column_totals, [30, 90])
assert np.array_equal(selected, [40, 50])
assert first[0] == 99 and values[0, 0] == 10
assert values[values >= 99].shape == (0,)
print("Module 7 checks passed")
# Transfer checkpoint: non-square data and approximate division.
transfer = np.array([[15, 30, 45], [20, 40, 60]])
assert transfer.sum(axis=0).shape == (3,)
assert transfer.sum(axis=1).shape == (2,)
assert np.array_equal(transfer.sum(axis=0), [35, 70, 105])
assert np.array_equal(transfer.sum(axis=1), [90, 120])
assert np.allclose(transfer / 60, [[0.25, 0.5, 0.75], [1/3, 2/3, 1.0]])
print("Non-square transfer checks passed")
Exit-check guide: For shape (2,3), sum(axis=1) has shape (2,). Multiplying a list by 2 repeats its entries; multiplying a numeric array by 2 doubles each number. A view is useful when a shared edit is intentional.