Aggregations along an axis
Add axis=0 to argmax and predict the three indices.
Aggregations like sum, mean, std and argmax collapse an array along an axis into fewer numbers. A seeded random generator, np.random.default_rng(seed), gives random-looking data that you can repeat exactly.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
For m = np.array([[1.0, 2.0], [3.0, 4.0]]), print the column means and the row sums.
Using default_rng(0), make an array of 5 dice rolls and print how many are above 3.
Replace negative numbers in x = np.array([-2.0, 3.0, -1.0, 5.0]) by 0 using np.where.
For x = np.array([2.0, 4.0, 6.0, 8.0, 10.0]) print the standard deviation the NumPy way and the pandas way (the sample version), rounded to 3 places.
Explain it without notes
What does axis mean in m.sum(axis=0) versus m.sum(axis=1) for a table?
What is the difference between max and argmax, and where is argsort used?
Why use np.random.default_rng(seed) rather than unseeded randomness in a data experiment?
What does np.where(cond, a, b) do and why is it better than a loop?
A sensor file has gaps stored as -999. Why is values.mean() wrong, and what do you do instead?
Why do np.std and pandas Series.std disagree on the same data?
Expected output
sum: 30.0 mean: 5.0
mean axis 0: [6. 4. 5.]
mean axis 1: [2. 8.]
std axis 1: [0.816 0.816]
argmax axis 1: [0 0] argmin: 1
min/max: 1.0 9.0
keepdims: [[2.0], [8.0]]
where: [['low', 'low', 'low'], ['high', 'high', 'high']]
where 3 args: [[0.0, 0.0, 0.0], [9.0, 7.0, 8.0]]
sorted idx: [1 2 0]