Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.4 — Aggregations, Statistics and Random Numbers
Python · Example 1 of 3

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.

01

For m = np.array([[1.0, 2.0], [3.0, 4.0]]), print the column means and the row sums.

02

Using default_rng(0), make an array of 5 dice rolls and print how many are above 3.

03

Replace negative numbers in x = np.array([-2.0, 3.0, -1.0, 5.0]) by 0 using np.where.

04

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

01

What does axis mean in m.sum(axis=0) versus m.sum(axis=1) for a table?

02

What is the difference between max and argmax, and where is argsort used?

03

Why use np.random.default_rng(seed) rather than unseeded randomness in a data experiment?

04

What does np.where(cond, a, b) do and why is it better than a loop?

05

A sensor file has gaps stored as -999. Why is values.mean() wrong, and what do you do instead?

06

Why do np.std and pandas Series.std disagree on the same data?

Aggregations along an axis
Sign in to run this example in your browser.

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]