Skip to content

Module 16 · External Libraries and APIs — topic 5 of 12

NumPy introduction

Fast numerical arrays with NumPy: creating arrays, vectorised arithmetic, shapes and reshaping, axis-wise aggregates, boolean masks, broadcasting, and why NumPy is much faster than lists for numbers.

Beginner 12 min read·Lesson 239 of 306 in Python Programming

Learning objectives

  • Create and inspect NumPy arrays
  • Use vectorised operations and aggregates along axes
  • Filter data with boolean masks

Definition

NumPy is the fundamental package for numerical computing in Python. Its ndarray stores numbers of one type in a compact block of memory and performs operations on whole arrays at C speed.

Introduction

Adding 10 to a million numbers in a Python loop takes noticeable time; in NumPy it's a single, almost instant expression: arr + 10.

Why it matters

pandas, Matplotlib, SciPy, scikit-learn and most machine-learning libraries are built on NumPy arrays. Understanding them unlocks the whole data ecosystem.

Detailed explanation

Install with python -m pip install numpy and import it as np by convention.

Create arrays from lists with np.array, or with helpers: np.arange, np.linspace, np.zeros, np.ones.

Every array has a dtype (element type, such as int64 or float64) and a shape (dimensions, such as (2, 3)). reshape changes the shape without copying data when possible.

Arithmetic is element-wise and vectorised: a * 10, a + b, a ** 2 operate on every element without a Python loop.

Aggregates such as sum, mean, min and max work on the whole array or along an axis: axis=0 goes down columns, axis=1 across rows.

Comparisons produce boolean arrays, which can be used as masks: arr[arr > 80] selects matching elements.

Broadcasting lets arrays of different but compatible shapes combine, such as adding a row of per-subject bonuses to every row of a marks table.

np.clip, np.where and many other functions apply common operations to whole arrays.

Syntax

Python
import numpy as np
a = np.array([1, 2, 3])
m = np.arange(6).reshape(2, 3)
m.sum(axis=0)
a[a > 1]
  • Arrays hold one dtype.
  • Operations are vectorised.
  • Masks filter elements.

Code examples

Array basics

Python
import numpy as np
a = np.array([1, 2, 3, 4])
print(a * 10, a + a, a.mean())
print(a.dtype, a.shape)
Output
[10 20 30 40] [2 4 6 8] 2.5
int64 (4,)

Requires NumPy.

Shapes and axes

Python
import numpy as np
m = np.arange(1, 7).reshape(2, 3)
print(m)
print(m.sum(axis=0), m.sum(axis=1), m.T.shape)
Output
[[1 2 3]
 [4 5 6]]
[5 7 9] [ 6 15] (3, 2)

Requires NumPy.

More examples

Analysing a marks table

Python
import numpy as np
marks = np.array([[72, 85, 91], [66, 78, 80], [90, 95, 88], [55, 60, 70]])
print(marks.mean(axis=0).round(1)) # per subject
print(marks.mean(axis=1).round(1)) # per student
top = marks.mean(axis=1) >= 80
print(top, marks[top].shape[0])
curved = np.clip(marks + 5, 0, 100)
print(curved.max(), (curved >= 75).sum())
print(np.linspace(0, 1, 5))
Output
[70.8 79.5 82.2]
[82.7 74.7 91.  61.7]
[ True False  True False] 2
100 9
[0.   0.25 0.5  0.75 1.  ]

Requires NumPy.

Step-by-step explanation

  • mean(axis=0) averages each column (subject); mean(axis=1) averages each row (student).
  • The boolean array top selects the rows of students averaging 80 or more.
  • Adding 5 to every mark and clipping at 100 happens in one vectorised step; summing a boolean array counts the True values.

Expected output

Running “Analysing a marks table” prints exactly:

TextOutput
[70.8 79.5 82.2]
[82.7 74.7 91. 61.7]
[ True False True False] 2
100 9
[0. 0.25 0.5 0.75 1. ]

Practical applications

  • Image processing (images are arrays of pixels).
  • Scientific simulations and machine-learning features.

Best practices

  • Think in whole-array operations.
  • Check shape and dtype when results look wrong.
  • Use masks instead of if statements inside loops.

Common mistakes

Looping over arrays

Avoid

for i in range(len(a)):
a[i] = a[i] * 2

Prefer

a = a * 2

Python loops lose NumPy's speed advantage.

Using and/or with arrays

Avoid

a[(a > 1) and (a < 4)]

Prefer

a[(a > 1) & (a < 4)]

and/or need single True/False values; use & and | with parentheses for element-wise logic.

Important notes

  • Integer arrays have fixed size and can overflow silently, unlike Python ints.

Key takeaways

  • ndarrays are fast typed arrays.
  • Operations and aggregates are vectorised, optionally per axis.
  • Boolean masks filter data.

Try it yourself

  1. 1
    Create a 5×5 array of the numbers 1–25 and print its diagonal and the sum of each column.
  2. 2
    Convert a list of Celsius temperatures to Fahrenheit with one NumPy expression.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.