Explain it simply
NumPy in plain language
NumPy is the Python library for doing arithmetic on lots of numbers quickly. Its central object is the ndarray: a grid of values that all share one type and sit side by side in memory. A Python list is a collection of pointers to separate objects, while a NumPy array stores the raw numbers in one tightly packed block.
It works like a spreadsheet where you apply one formula to a whole column instead of editing each cell by hand. In NumPy, writing scores * 2 doubles every cell, and the loop runs inside compiled C code, which is why it is often many times faster than a Python loop.
Problem → Why → Solution
The problem: lists and loops get slow and messy
Imagine storing quiz marks for 3 students and 4 quizzes as a list of lists. The average per student, the average per quiz and a percentage conversion each need their own nested loop. Grow that to a hundred thousand students and the loops take seconds, and every hand-written index is another chance for an off-by-one bug.
scores = [[40, 35, 48, 42], [28, 31, 25, 30], [45, 50, 47, 49]]
quiz_means = []
for q in range(4):
total = 0
for row in scores:
total += row[q]
quiz_means.append(total / len(scores))
percent = [[s / 50 * 100 for s in row] for row in scores]
doubled = scores * 2 # surprise: repeats the list, does not double the marksWhy NumPy fits this job
The loops describe how to compute rather than what you want, and the last line is a trap: on a list, * repeats the list instead of doing maths. With NumPy, scores.mean(axis=0) is a single line for the quiz averages, and scores * 2 really doubles every mark.
Core concept: shape, dtype, axis and broadcasting
Every array has two attributes you should check first. shape is a tuple giving the number of elements along each dimension: a table with 3 rows and 4 columns has shape (3, 4). dtype is the type of every cell, such as int64, float64 or bool. Because an array holds exactly one dtype, mixing integers and floats upgrades everything to float64. Fixed-size integer dtypes also have limits: unlike a Python int, an int8 value silently wraps around after 127.
A vectorized operation applies +, -, *, /, ** or a comparison element by element, between two arrays or between an array and a number. a * b is not matrix multiplication; it multiplies matching positions. Use a @ b when you want the matrix product. A comparison returns an array of True and False values, and using it as a mask, scores[mask], selects only the elements where the mask is True.
Reductions such as sum, mean, max, min and std take an axis argument, which names the dimension that gets collapsed. On a (3, 4) array, axis=0 collapses the rows and leaves 4 results, one per column, while axis=1 collapses the columns and leaves 3 results, one per row.
| Expression | Result on a (3, 4) array |
|---|---|
| a.sum() | a single number (all 12 cells) |
| a.mean(axis=0) | shape (4,): one mean per column |
| a.mean(axis=1) | shape (3,): one mean per row |
Broadcasting is the rule that lets arrays of different shapes work together. NumPy compares shapes from the right: two dimensions are compatible when they are equal or when one of them is 1. So (3, 4) plus (4,) stretches the (4,) vector across all three rows. (3, 4) plus (3,) fails because 4 and 3 do not match; to add one value per row you reshape it to (3, 1) first.
- Check shape and dtype first
- An operation touches every cell at once
- axis picks the dimension to collapse
- Mismatched shapes broadcast from the right
After every line, ask what shape the result will have; most NumPy bugs start as a shape surprise.
General pattern
import numpy as np
arr = np.array(nested_values, dtype=np.float64)
arr.shape, arr.dtype
result = arr * factor + offset # element-wise
per_column = arr.mean(axis=0) # collapse rows
per_row = arr.sum(axis=1) # collapse columns
subset = arr[arr > threshold] # boolean mask
view = arr[:, col] # slice = view
safe = arr[:, col].copy() # independent copyBuild the array, check its shape and dtype, then replace loops with expressions, axis-aware reductions and masks. Add .copy() whenever a slice must be modified independently.
Worked example: a table of quiz scores
The program below uses a table of 3 students and 4 quizzes, each marked out of 50. Every loop from the problem section becomes one expression, and the final lines prove that editing a slice also changes the original array.
import numpy as np
# 3 students x 4 quizzes, each quiz out of 50
scores = np.array([
[40, 35, 48, 42],
[28, 31, 25, 30],
[45, 50, 47, 49],
])
print("shape:", scores.shape, "dtype:", scores.dtype)
percent = scores / 50 * 100 # one expression, every cell
print("student 0 (%):", percent[0])
print("mean per student:", scores.mean(axis=1))
print("mean per quiz: ", scores.mean(axis=0))
bonus = np.array([2, 0, 5, 0]) # shape (4,) is stretched over 3 rows
curved = np.minimum(scores + bonus, 50)
print("curved:")
print(curved)
passed = scores.mean(axis=1) >= 35 # boolean mask, one per student
print("passed:", passed, "count:", passed.sum())
print("passing rows:")
print(scores[passed])
quiz3 = scores[:, 2] # slicing gives a VIEW
quiz3[0] = 0
print("after editing the slice, scores[0, 2] =", scores[0, 2])Code breakdown
- Inspect first
print("shape:", scores.shape, "dtype:", scores.dtype)Prints (3, 4) and int64. Only integers were supplied, so the dtype is an integer type, int64 on most 64-bit platforms.
- Vectorized maths
percent = scores / 50 * 100 # one expression, every cellAll 12 cells are computed at once. Division always produces floats, so the result is float64 and prints with trailing dots such as 80.
- Choose the axis
print("mean per student:", scores.mean(axis=1))axis=1 collapses the quiz columns, giving one average per student. The next line uses axis=0 to get one average per quiz.
- Broadcast a vector
curved = np.minimum(scores + bonus, 50)bonus has shape (4,), so it is stretched across every row: quiz 1 gains 2 marks and quiz 3 gains 5. np.minimum then caps each cell at 50.
- Mask rows
print(scores[passed])passed is a shape (3,) array with one True or False per student. Used as an index it returns only the True rows, as a new copy. passed.sum() counts True as 1.
- A view, not a copy
quiz3 = scores[:, 2] # slicing gives a VIEWBasic slicing returns a view that looks at the same memory instead of copying it. That is why quiz3[0] = 0 also turns scores[0, 2] into 0.
shape: (3, 4) dtype: int64
student 0 (%): [80. 70. 96. 84.]
mean per student: [41.25 28.5 47.75]
mean per quiz: [37.66666667 38.66666667 40. 40.33333333]
curved:
[[42 35 50 42]
[30 31 30 30]
[47 50 50 49]]
passed: [ True False True] count: 2
passing rows:
[[40 35 48 42]
[45 50 47 49]]
after editing the slice, scores[0, 2] = 0Reading broadcasting through shapes
Broadcasting (3, 4) with (4,) and (3, 1)
----------------------------------------
scores (3, 4) bonus (4,) -> treated as (1, 4)
[[40 35 48 42] [ 2 0 5 0] copied down 3 rows
[28 31 25 30] + [ 2 0 5 0]
[45 50 47 49]] [ 2 0 5 0]
scores (3, 4) row_offset (3, 1)
[[40 35 48 42] [[ 1] copied across 4 columns
[28 31 25 30] + [ 3]
[45 50 47 49]] [ 0]]
rule: compare shapes from the right; sizes must match or be 1When you want to add one value per row, adding a shape (3,) array directly raises 'operands could not be broadcast together'. Turn it into a column with arr[:, np.newaxis] or reshape(3, 1). A reduction with keepdims=True, such as mean(axis=1, keepdims=True), returns the (3, 1) shape directly, which is handy for subtracting each row's mean.
In real projects
NumPy in real projects
Even when you never import it directly, most data tools in Python are built on NumPy. pandas columns are backed by arrays, scikit-learn expects a 2D array of features, and image libraries hand you a picture as an array of shape (height, width, 3).
- Sensor or finance data: one row per day, mean(axis=1) for daily averages, and a boolean mask to find readings above a limit.
- Machine-learning preprocessing: standardising each column with (x - mean) / std relies on broadcasting, and data is often cast to float32 before it reaches a model.
- Image processing: brightening a whole picture is one addition, followed by np.clip to keep values inside 0-255 so a uint8 array does not overflow.
Common mistakes
Common NumPy mistakes
Treating a slice as a copy
After first_col = data[:, 0], editing first_col also edits data. Inside a function this silently corrupts the caller's array, so write data[:, 0].copy() when you need an independent piece. Boolean and fancy indexing behave the opposite way: they return copies, so modifying the result of data[mask] leaves data untouched, while assigning directly with data[mask] = value does change it.
Using the wrong axis
Writing axis=0 when you want one average per student does not raise an error; it quietly returns four quiz averages instead. Check the result's shape: three students should give three values.
Letting broadcasting hide a shape bug
Subtracting shapes (3,) and (3, 1) does not fail; it produces a (3, 3) table. Taking row means without keepdims and subtracting them is a classic way to hit this, so add assert result.shape == expected at important steps.
Best practices
Best practices
- Import with the conventional import numpy as np and print the shape and dtype of every new array.
- Avoid Python for loops over the cells of large arrays; prefer expressions, reductions and masks.
- Compare floats with np.allclose or np.isclose rather than ==.
- For random data, create rng = np.random.default_rng(seed) so results can be reproduced.
Mini challenge
Mini challenge: a temperature sensor table
A sensor recorded 6 readings a day for 4 days. Without loops, use NumPy expressions to compute each day's temperature range, standardise every column, and count readings that are too hot. Finally clip the data in place with a mask while protecting the original in a backup copy.
- daily_range returns max - min for each row, shape (4,)
- standardize_columns uses keepdims=True and returns shape (4, 6)
- hot_readings counts readings above a limit with a boolean mask and returns an int
- Take a backup with .copy() before clipping and print the original value from it
import numpy as np
# 4 days x 6 readings (degrees C)
temps = np.array([
[21.0, 22.5, 25.1, 27.8, 26.0, 23.2],
[19.5, 20.1, 24.0, 29.4, 28.8, 24.5],
[22.2, 23.0, 26.7, 31.2, 30.1, 25.9],
[18.9, 19.4, 21.8, 24.6, 23.7, 20.3],
])
def daily_range(t: np.ndarray) -> np.ndarray:
# TODO: max minus min along the right axis
...
def standardize_columns(t: np.ndarray) -> np.ndarray:
# TODO: (t - column mean) / column std, using keepdims=True
...
def hot_readings(t: np.ndarray, limit: float) -> int:
# TODO: count cells above limit with a mask
...
# TODO: print the results, then back up temps and clip values above 30 in placeExpected: Daily range [6.8 9.9 9. 5.7], z shape (4, 6), hottest day index 2, 4 readings above 28, and the backup still holds 31.2 while the clipped array shows 30.0.
Show hint
One result per row means axis=1. Taking the column mean with keepdims=True gives shape (1, 6), which broadcasts against (4, 6). (t > limit).sum() counts the True values.
Show solution
import numpy as np
# 4 days x 6 readings (degrees C) from one sensor
temps = np.array([
[21.0, 22.5, 25.1, 27.8, 26.0, 23.2],
[19.5, 20.1, 24.0, 29.4, 28.8, 24.5],
[22.2, 23.0, 26.7, 31.2, 30.1, 25.9],
[18.9, 19.4, 21.8, 24.6, 23.7, 20.3],
], dtype=np.float64)
def daily_range(t: np.ndarray) -> np.ndarray:
"""Max minus min for every day (one value per row)."""
return t.max(axis=1) - t.min(axis=1)
def standardize_columns(t: np.ndarray) -> np.ndarray:
"""Z-score each reading slot so columns become comparable."""
mean = t.mean(axis=0, keepdims=True) # shape (1, 6)
std = t.std(axis=0, keepdims=True)
return (t - mean) / std # broadcasts (4, 6) with (1, 6)
def hot_readings(t: np.ndarray, limit: float) -> int:
return int((t > limit).sum())
print("daily range:", daily_range(temps).round(1))
z = standardize_columns(temps)
print("z shape:", z.shape)
print("column means after z-score:", np.abs(z.mean(axis=0)).max() < 1e-12)
print("hottest day index:", int(temps.max(axis=1).argmax()))
print("readings above 28:", hot_readings(temps, 28.0))
backup = temps.copy() # a real copy, not a view
temps[temps > 30] = 30 # clip in place with a mask
print("original kept in backup:", backup[2, 3], "clipped:", temps[2, 3])Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A NumPy array has one shape and one dtype, and operations act on every cell at once.
- axis selects the dimension to collapse; always check the shape of the result.
- Broadcasting compares shapes from the right; sizes must be equal or 1.
- Basic slices are views, masks and fancy indexing give copies; use .copy() when you need independence.
NumPy — Quickstart — NumPy