Stop 03 · Python for Data ScienceTopics · 2/9

NumPy for Numerical Computing

Part of the Data Science Roadmap

In short

Plain Python loops are slow when you have a million numbers. NumPy does the same maths on whole arrays at once, often many times faster, and pandas is built on top of it.

The foundational library for fast, vectorized array operations in Python — Pandas, scikit-learn and most ML frameworks are built directly on top of NumPy arrays.

The mascot presses a giant stamp onto a tall stack of answer sheets.

Think of it like this

The teacher's giant stamp

Adding 5 grace marks by opening every answer sheet one by one takes all evening. Imagine one giant stamp that adds 5 to the whole stack at once. NumPy works like that stamp: one operation, every number, no loop.

Watch it happen

Whole-array maths, no loops

72
0
45
1
88
2
30
3
64
4

1/4A NumPy array of five marks. All the same type, stored side by side in memory.

The big ideas

What you need to know

Vectorised is fast

Operations run in optimised compiled code over the whole array, instead of a slow Python loop.

Shape matters

arr.shape tells you rows and columns. reshape changes the layout without changing the data.

Boolean masks filter

arr[arr > 50] keeps matching values. The same idea powers filtering in pandas.

Broadcasting stretches

Adding a single number or a matching row to a 2D array stretches it across automatically.

See it in code

Walk through the code

python
1import numpy as np2 3marks = np.array([72, 45, 88, 30, 64])4marks = marks + 5                  # grace marks for everyone5print(marks.mean(), marks.max())   # 64.8 936print(marks[marks >= 50])          # [77 50 93 69]

1/3Create an array and add 5 to every element at once.

No loop anywhere. Each line works on all five numbers, and it would be just as short for five million.

Save yourself the pain

Common mistakes

Oops

Writing a for loop to add or multiply every element.

Do this instead

Use array maths like arr * 2 or np.sqrt(arr). It's shorter and much faster.

Oops

Using 'and' or 'or' to combine array conditions.

Do this instead

Use & and | with brackets: arr[(arr > 50) & (arr < 90)].

Your mission

Race a loop against NumPy

~15 min

Quick check

a = np.array([1, 2, 3]). What does a * 2 return?

Go deeper

  1. 1Practice creating arrays and performing vectorized math without explicit loops.
  2. 2Learn broadcasting rules — how NumPy applies operations across differently-shaped arrays.
  3. 3Time a vectorized NumPy operation against an equivalent Python loop to see the speed difference.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge