Command Palette

Search for a command to run...

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

Seeded random numbers

Change the seed 42 to 43 and see every number change; keep 42 and the output never changes.

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?

Seeded random numbers
Sign in to run this example in your browser.

Expected output

same seed A: [0.774  0.4389 0.8586]
same seed B: [0.774  0.4389 0.8586]
integers: [6 4 5 6 4]
normal: [-0.891 -0.455 -0.992]
choice: ['d' 'c']
permutation: [3 8 4 6 5 2 0 7 1 9]
mean ~50: 49.33 std ~10: 9.45