AI Hints
Statistics & Math for ML · Lesson 5 of 138

NumPy in a Minute

Arrays of numbers.

⏱ 2 min read▶ Video at 4:44🎓 Free
Watch this lesson in the Statistics & Math for ML courseWatch on YouTube ↗Full Statistics & Math for ML course

Python lists are great, but for maths on lots of numbers, everyone uses NumPy. It stores numbers in arrays, and does maths on the whole array at once, very fast. We'll use it throughout the course.

NumPy in a Minute
From the video: NumPy in a Minute
  • Lists are slow for maths
  • NumPy arrays
  • Maths on everything at once

Arrays

We import NumPy as NP, which is the usual nickname. NP dot array turns a list into an array. Now arithmetic works on every number at once. Adding five adds it to every score. And comparing gives an array of trues and falses. Run it.

arrays.pypython
import numpy as np

scores = np.array([55, 72, 90, 40, 81])

print(scores + 5)
print(scores * 2)
print(scores >= 60)
Output
[60 77 95 45 86]
[110 144 180  80 162]
[False  True  True False  True]

Random samples

NumPy can also make random numbers, which we'll use to simulate data. We make a random generator with a seed, so we get the same numbers every time. Normal draws heights around one seventy, with a spread of eight. Run it. Ten thousand pretend heights, in one line.

fake_heights.pypython
import numpy as np

rng = np.random.default_rng(42)
heights = rng.normal(170, 8, size=10_000)

print(heights.shape)
print(heights[:5].round(1))
Output
(10000,)
[172.4 161.7 176.  177.5 154.4]

Summary

NumPy arrays do maths on every number at once, and its random generator makes data we can experiment with. Next, the first summary of any dataset.

Key takeaways
  • np.array
  • Maths on whole arrays
  • rng.normal for fake data
Next up: Your First Summary — count, sum, min, max