NumPy Essentials — Arrays & Vectorization
IntermediateNumPy arrays store homogeneous data in contiguous memory and operate on whole arrays at C speed — vectorization, broadcasting and boolean masks replace Python loops.
Overview
NumPy is the foundation of Python's data/AI stack (pandas, scikit-learn, PyTorch all build on it). Its ndarray is a typed, contiguous block — far smaller and faster than a list of Python objects — and operations apply elementwise without loops (vectorization). Broadcasting stretches shapes automatically (matrix + row vector just works), and boolean masking filters data in one expression. Even for pure-backend roles, NumPy literacy signals you can survive the data-adjacent parts of the job.
Arrays, Vectorization & Masks
Create from lists or generators (zeros, arange, linspace). Operations and comparisons broadcast elementwise; masks select rows matching conditions — no loops anywhere.
import numpy as np
marks = np.array([67, 82, 45, 91, 38, 74]) # dtype=int64
# Vectorized ops — whole array at once, C speed
curved = marks + 5 # add to every element
print(curved.mean(), curved.max()) # 71.16... 96
# Boolean masking — filter in one expression
passed = marks[marks >= 40] # array([67, 82, 45, 91, 74])
print((marks >= 40).sum()) # 5 — True counts as 1
marks[marks < 40] = 40 # grace marks, in place!
# 2D — rows = students, cols = subjects
scores = np.array([[80, 90, 70],
[60, 85, 95]])
print(scores.shape) # (2, 3)
print(scores.mean(axis=0)) # per-subject: [70. 87.5 82.5]
print(scores.mean(axis=1)) # per-student: [80. 80.]
# Speed: sum of 10 million squares
big = np.arange(10_000_000)
total = (big ** 2).sum() # ~30x faster than a Python loopBroadcasting & Useful Toolbox
Shapes align from the right; dimensions of 1 stretch. reshape/argmax/argsort/where/random cover most day-one needs. Slices are VIEWS — modifying them modifies the original.
import numpy as np
# Broadcasting: (2,3) matrix + (3,) row — row applies to each row
scores = np.array([[80, 90, 70], [60, 85, 95]])
bonus = np.array([5, 0, 10])
print(scores + bonus) # [[85 90 80], [65 85 105]]
# Normalize each column to 0-1 (a real ML preprocessing step)
mn, mx = scores.min(axis=0), scores.max(axis=0)
print((scores - mn) / (mx - mn))
print(np.where(scores > 75, "good", "work")) # elementwise choice
top_student = scores.sum(axis=1).argmax() # index of best row
a = np.arange(10)
view = a[2:5] # a VIEW, not a copy!
view[0] = 99
print(a[2]) # 99 — original changed
safe = a[2:5].copy() # explicit copy when needed
r = np.random.default_rng(42)
sample = r.integers(1, 7, size=5) # 5 dice rolls, reproducibleKey Points to Remember
- 1ndarray = one dtype, contiguous memory — 10-100x faster than list loops
- 2Vectorize: arr * 2, arr >= 40, arr.mean(axis=...) — loops are a smell in NumPy
- 3Boolean masks filter and assign: arr[arr < 40] = 40
- 4Slices are views (share memory); .copy() when you need independence
Interview Questions
Sign in to ask AriaWhy is NumPy so much faster than Python lists for numeric work?
Explain broadcasting — when do a (3,4) and a (4,) array combine?
NumPy slices are views — what bug can this cause?
Ask Aria about NumPy Essentials — Arrays & Vectorization
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.