NumPy
import numpy as np
a = np.array([1, 2, 3, 4])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.
| dtype | Holds | Example |
|---|---|---|
int64 | whole numbers | np.array([1, 2, 3]) |
float64 | decimals (and np.nan) | np.array([1.5, 2.0]) |
bool | True / False | a > 2 |
<U5 | text up to 5 characters | np.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.vstackstacks them as rows,np.hstackside by side, andnp.column_stackturns 1-D arrays into columns.a.reshape(2, -1): the-1means "work this size out for me".m.flatten()orm.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 fromxwhere the condition is True and fromyelsewhere;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)andnp.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
| Function | Does |
|---|---|
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, indexingm[row, col]andaxis=handle 2-D data; masks likea[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.
Try it yourselfExample 1: Arrays vs lists
The same * 2 does very different things to a list and an array.
Output appears hereDouble them all
Fill the blanks so NumPy doubles every number at once and prints [2 4 6].
import numpy as np a = np.([1, 2, 3]) print(a 2)
A list isn't an array
This should add 10 to every price and print [30 45 60], but it crashes. Fix it.
Example 2: Statistics in one line
Daily temperatures for a week.
Output appears hereQuick statistics
Fill the blanks so the program prints the mean and the largest value: 6.0 10.
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.
Output appears hereRow totals
Make a 2-D array [[1, 2, 3], [4, 5, 6]] and print the total of each row: [ 6 15].
Example 4: Filtering with masks
A comparison gives a True/False array that selects elements.
Output appears herePassing marks
Using a mask, print only the marks of 40 or more from np.array([35, 72, 40, 18, 90]): [72 40 90].
Example 5: Random data
The seed makes the "random" numbers the same every run, which helps when checking work.
Output appears hereExample 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.
Output appears hereExample 7: Slicing rows, columns and blocks
A 4×5 table of seat numbers. Each slice is rows first, then columns.
Output appears hereExample 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.
Output appears hereExample 9: Joining and reshaping
Two weeks of daily sales joined into one array, then reshaped into a table of weeks by days.
Output appears hereExample 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.
Output appears hereExample 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.
Output appears hereExample 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.
Output appears here2Level 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.
Example 13: Broadcasting, where and ranking
Rows are students, columns are subjects. No Python loops anywhere.
Output appears here3Level 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.
Output appears hereExample 15: Views, copies, dtypes and solving equations
Changing the slice changed a; changing the masked copy didn't.
Output appears herenp.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.What does this print?
import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a[a % 2 == 1] * 10)
50 graded problems are waiting in Topic Practice.