LearnPy Hub
Data ScienceIntermediateLesson 25 of 32

NumPy

Watch the ideaMaths on a whole array at once
import numpy as np
a = np.array([1, 2, 3, 4])
a
10
21
32
43

A NumPy array is a row of numbers of the same type.

1Level 1 · BasicsBasics

NumPy is the foundation of data science in Python. It gives you the array: a grid of numbers that you can do maths on all at once, much faster than looping over a list. pandas, Matplotlib, scikit-learn and PyTorch are all built on NumPy.

The first time you run a NumPy example, the browser downloads the library (a few MB), so give it a moment.

Creating arrays

import numpy as np        # np is the standard nickname

a = np.array([1, 2, 3, 4])
zeros = np.zeros(5)           # [0. 0. 0. 0. 0.]
steps = np.arange(0, 10, 2)   # [0 2 4 6 8]  like range()
grid = np.linspace(0, 1, 5)   # 5 evenly spaced numbers from 0 to 1

Maths on whole arrays (vectorization)

With a list, [1, 2, 3] * 2 repeats the list. With an array, operations apply to every element:

a * 2        # [2 4 6 8]
a + a        # [2 4 6 8]
a ** 2       # [ 1  4  9 16]
np.sqrt(a)   # square root of each

No loop needed. This style is called vectorization, and it's often 10–100× faster than a Python loop.

Statistics in one call

a.sum(), a.mean(), a.min(), a.max(), a.std(), np.median(a), and a.argmax() (the position of the largest value).

2-D arrays (matrices)

m = np.array([[1, 2, 3],
              [4, 5, 6]])
m.shape        # (2, 3): 2 rows, 3 columns
m[1, 2]        # 6: row 1, column 2
m[:, 0]        # first column: [1 4]
m.sum(axis=0)  # down each column: [5 7 9]
m.sum(axis=1)  # across each row:  [ 6 15]
m.T            # transpose (swap rows and columns)

reshape() changes the shape, e.g. np.arange(6).reshape(2, 3).

Boolean masks: filtering

Comparing an array gives an array of True/False, which you can use to pick elements:

marks = np.array([72, 35, 88, 40, 19])
marks >= 40            # [ True False  True  True False]
marks[marks >= 40]     # [72 88 40]
(marks >= 40).sum()    # 3, since True counts as 1

This "mask" idea is exactly how filtering works in pandas too.

Random numbers

rng = np.random.default_rng(42) makes a random generator (the 42 makes results repeatable). Then use rng.integers(1, 7, size=10) or rng.normal(0, 1, size=100).

Data types (dtype)

Every array has one dtype, the type of all its elements. a.dtype shows it, and a.astype(float) makes a converted copy.

dtypeHoldsExample
int64whole numbersnp.array([1, 2, 3])
float64decimals (and np.nan)np.array([1.5, 2.0])
boolTrue / Falsea > 2
<U5text up to 5 charactersnp.array(["CSE", "EEE"])

Useful attributes: a.ndim (number of dimensions), a.shape, a.size (total elements) and a.dtype.

Indexing and slicing in detail

Slicing works like lists, start:stop:step, in every dimension:

a = np.arange(10)          # [0 1 2 3 4 5 6 7 8 9]
a[2:5]                     # [2 3 4]
a[::2]                     # [0 2 4 6 8]  every second
a[::-1]                    # reversed
m = np.arange(12).reshape(3, 4)
m[0]                       # first row
m[:, -1]                   # last column
m[1:, :2]                  # rows 1-2, columns 0-1 (a 2×2 block)
a[[1, 4, 7]]               # "fancy" indexing: pick positions 1, 4 and 7

Broadcasting: arrays of different shapes

When shapes differ, NumPy broadcasts: it stretches the smaller array to fit, without copying data. Compare shapes from the right: two sizes are compatible if they're equal or one of them is 1.

prices = np.array([[10, 20, 30],      # shape (2, 3): 2 shops, 3 items
                   [12, 18, 33]])
tax = np.array([1.05, 1.10, 1.00])    # shape (3,): one rate per item
prices * tax                          # each column times its own rate
prices - prices.mean(axis=0)          # centre every column on its mean

A shape of (3,) against (2, 3) works; (2,) against (2, 3) doesn't, unless you make it a column with v.reshape(-1, 1) or v[:, None].

Combining and reshaping

  • np.concatenate([a, b]) joins arrays end to end; np.vstack stacks them as rows, np.hstack side by side, and np.column_stack turns 1-D arrays into columns.
  • a.reshape(2, -1): the -1 means "work this size out for me".
  • m.flatten() or m.ravel() turns any shape back into one row.

Sorting, searching and choosing

  • np.sort(a) returns a sorted copy; np.argsort(a) returns the positions that would sort it, which lets you sort one array by another.
  • np.where(cond, x, y) picks from x where the condition is True and from y elsewhere; np.where(cond) alone gives the positions.
  • np.select([c1, c2], ["A", "B"], default="C") handles several conditions, like an if/elif/else for whole arrays.
  • np.any(a > 90) and np.all(a >= 0) answer yes/no questions about the whole array.

Missing values: NaN

Missing numbers are stored as np.nan ("not a number") in float arrays. Any maths with NaN gives NaN, so a.mean() becomes nan. Use the NaN-safe versions np.nanmean, np.nansum, np.nanmax, and find the gaps with np.isnan(a). Note that np.nan == np.nan is False, so always test with np.isnan.

Handy functions

FunctionDoes
np.cumsum(a)running total
np.diff(a)difference between neighbours (day-to-day change)
np.percentile(a, 90)the value 90% of the data is below
np.clip(a, 0, 100)limit values to a range
np.round(a, 1)round every element
np.unique(a, return_counts=True)distinct values and how often each appears
a @ b or np.dot(a, b)matrix multiplication / dot product
Key points: import numpy as np; arrays do maths element by element without loops; .shape, indexing m[row, col] and axis= handle 2-D data; masks like a[a > 0] filter.

See it in actionMaths on the whole array at once

One line changes every element. Arrays are drawn as rows of boxes, and 2-D arrays as tables.

Step-by-step

Try it yourselfExample 1: Arrays vs lists

The same * 2 does very different things to a list and an array.

example_1.py
Output appears here
Fill in the blanks

Double them all

Fill the blanks so NumPy doubles every number at once and prints [2 4 6].

blanks.py
import numpy as np
a = np.([1, 2, 3])
print(a  2)
Fix the bug

A list isn't an array

This should add 10 to every price and print [30 45 60], but it crashes. Fix it.

buggy.py

Example 2: Statistics in one line

Daily temperatures for a week.

example_2.py
Output appears here
Fill in the blanks

Quick statistics

Fill the blanks so the program prints the mean and the largest value: 6.0 10.

blanks.py
import numpy as np
a = np.array([2, 4, 8, 10, 6])
print(a.(), a.())

Example 3: 2-D arrays

Rows are students, columns are subjects. axis=0 works down columns; axis=1 across rows.

example_3.py
Output appears here
Your turn

Row totals

Make a 2-D array [[1, 2, 3], [4, 5, 6]] and print the total of each row: [ 6 15].

my_code.py

Example 4: Filtering with masks

A comparison gives a True/False array that selects elements.

example_4.py
Output appears here
Your turn

Passing marks

Using a mask, print only the marks of 40 or more from np.array([35, 72, 40, 18, 90]): [72 40 90].

my_code.py

Example 5: Random data

The seed makes the "random" numbers the same every run, which helps when checking work.

example_5.py
Output appears here

Example 6: Types and attributes

Every array knows its shape, size and dtype. astype makes a converted copy; mixing types upgrades everything to the most general one.

example_6.py
Output appears here

Example 7: Slicing rows, columns and blocks

A 4×5 table of seat numbers. Each slice is rows first, then columns.

example_7.py
Output appears here

Example 8: Broadcasting in practice

Prices for 3 items in 2 shops. A row of rates applies to every row, a column of discounts to every column, all without loops.

example_8.py
Output appears here

Example 9: Joining and reshaping

Two weeks of daily sales joined into one array, then reshaped into a table of weeks by days.

example_9.py
Output appears here

Example 10: Sorting, ranking and choosing

argsort sorts one array by another. np.select gives each mark a grade, like if/elif/else for the whole array.

example_10.py
Output appears here

Example 11: Missing values with NaN

Two sensor readings are missing. Ordinary mean() gives nan; the nan-functions skip the gaps, and np.isnan finds them.

example_11.py
Output appears here

Example 12: Mini project: a month of shop sales

Running totals, day-to-day change, percentiles and a weekly table, all from one array of random sales.

example_12.py
Output appears here

2Level 2 · IntermediateShapes, axes and broadcasting

reshape and axes

a.reshape(3, 4) rearranges 12 numbers into 3 rows and 4 columns. Many functions take an axis: axis=0 works down the columns (one result per column), axis=1 works across each row.

Broadcasting

NumPy stretches smaller arrays to match bigger ones. A (3, 4) table minus a (4,) row of column averages subtracts each column's average from that column, with no loops.

Fancy indexing and np.where

a[[0, 2]] picks rows 0 and 2. np.where(marks >= 40, "pass", "fail") chooses element by element. np.argsort gives the order that would sort the array, which is handy for ranking.

See it in actionReshaping and summing along axes

Watch the flat array become a table, then shrink to column and row totals.

Step-by-step

Example 13: Broadcasting, where and ranking

Rows are students, columns are subjects. No Python loops anywhere.

example_13.py
Output appears here

3Level 3 · AdvancedSpeed, views and linear algebra

Why vectorization is fast

A NumPy operation runs one compiled loop in C over a block of memory, instead of thousands of Python steps. It's often 50 to 100 times faster, so always look for the whole-array way first.

Views vs copies

Slicing (a[1:3]) gives a view: change it and the original changes. Fancy indexing and masks give copies. Call .copy() when you need independence.

dtypes

Every array has one type (int64, float64, bool). Choosing float32 or uint8 halves or eighths memory, as with images.

Linear algebra

A @ B multiplies matrices; np.linalg.solve(A, b) solves equations like 2x + y = 5, x − y = 1.

Example 14: Loop vs vectorized timing

Both compute the same total; compare the times.

example_14.py
Output appears here

Example 15: Views, copies, dtypes and solving equations

Changing the slice changed a; changing the masked copy didn't.

example_15.py
Output appears here
GotchaArrays hold one type. np.array([1, 2.5]) turns everything into floats, and mixing text with numbers turns everything into text. Also, slices of an array are views: changing b = a[:3] changes a too. Use a[:3].copy() if you need a separate array.
Exercise · predict the output

What does this print?

import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a[a % 2 == 1] * 10)
Quick quiz · 7 questions
1. What does np.array([1, 2, 3]) * 2 give?
2. For m with shape (3, 4), how many rows does it have?
3. What does m.sum(axis=0) compute for a 2-D array?
4. How do you keep only the values greater than 50 in array a?
5. Why are NumPy operations usually faster than Python loops?
6. For a of shape (2, 3) and b of shape (3,), what is the shape of a + b?
7. What does np.nanmean([2, np.nan, 4]) return?
Ready to practice numpy?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python NumPy · LearnPy Hub