Day 8: NumPy Arrays
✅ Today you will learn
- Why NumPy is 50× faster than lists
- Create arrays: array, arange, linspace, zeros, ones
- shape, ndim, size and dtype
- Index, slice and filter with boolean masks
- reshape, flatten, stack and concatenate
🏢 In the real world
A weather company stores readings from 2,000 sensors every 10 minutes – millions of numbers a day. NumPy arrays let them compute daily averages for all sensors in a fraction of a second; plain Python lists would take minutes.
Why NumPy?
NumPy stores numbers of one type in one continuous block of memory and runs maths in fast C code. Pandas, scikit-learn and almost every data library are built on top of it.
import time
import numpy as np
n = 2_000_000
py_list = list(range(n))
arr = np.arange(n)
t = time.perf_counter(); s1 = sum(x * 2 for x in py_list); t1 = time.perf_counter() - t
t = time.perf_counter(); s2 = (arr * 2).sum(); t2 = time.perf_counter() - t
print("Same answer:", s1 == s2)
print("NumPy is roughly", round(t1 / t2), "times faster on this computer")The exact speed-up depends on your machine, but it is usually tens of times faster.
Creating arrays
import numpy as np marks = np.array([78, 92, 65, 88, 71]) print(marks, marks.dtype) print(np.arange(0, 20, 5)) # start, stop, step print(np.linspace(0, 1, 5)) # 5 equal points from 0 to 1 print(np.zeros(3), np.ones((2, 3))) print(np.full(4, 99), np.eye(3, dtype=int))
shape, ndim, size, dtype
import numpy as np
# rows = 4 students, columns = maths, science, english
scores = np.array([[78, 82, 69],
[92, 88, 95],
[65, 70, 58],
[88, 79, 84]])
print("shape:", scores.shape, "| ndim:", scores.ndim, "| size:", scores.size, "| dtype:", scores.dtype)
prices = np.array([499, 1299.5, 89])
print(prices.dtype, prices.astype(int))| maths | science | english | |
|---|---|---|---|
| 0 | 78 | 82 | 69 |
| 1 | 92 | 88 | 95 |
| 2 | 65 | 70 | 58 |
| 3 | 88 | 79 | 84 |
Indexing and slicing
import numpy as np scores = np.array([[78, 82, 69], [92, 88, 95], [65, 70, 58], [88, 79, 84]]) print(scores[1]) # second student print(scores[1, 2]) # second student, english print(scores[:, 0]) # all maths marks print(scores[1:3, :2]) # students 1–2, maths & science print(scores[-1, -1]) # last student, last subject
Boolean masks – filtering without loops
import numpy as np
temps = np.array([31.2, 34.8, 41.5, 39.0, 44.1, 29.7, 42.3])
hot = temps > 40
print(hot)
print("Hot days:", temps[hot], "| count:", hot.sum())
print("Mild days:", temps[(temps >= 30) & (temps <= 40)])
print("Index of hottest day:", temps.argmax())
temps[temps > 43] = 43 # cap extreme sensor values
print(temps)For arrays write (a > 1) & (a < 5) with brackets. Python’s and works only on single True/False values and gives an error with arrays.
Reshape, stack and concatenate
import numpy as np monthly = np.arange(1, 13) * 100 # 12 months of sales print(monthly.reshape(4, 3)) # 4 quarters × 3 months print(monthly.reshape(4, -1).sum(axis=1)) # quarter totals (-1 = work it out) a, b = np.array([1, 2, 3]), np.array([4, 5, 6]) print(np.vstack([a, b])) print(np.hstack([a, b]), np.concatenate([a, b]).shape) print(monthly.reshape(4, 3).flatten()[:5])
Real example: class report card
import numpy as np
names = np.array(["Aman", "Priya", "Rahul", "Sneha", "Kabir"])
scores = np.array([[78, 82, 69], [92, 88, 95], [35, 41, 28], [88, 79, 84], [55, 62, 60]])
avg = scores.mean(axis=1)
print("Averages:", avg.round(1))
print("Topper :", names[avg.argmax()], avg.max().round(1))
print("Failed (<40):", names[avg < 40])
print("Subject averages (M, S, E):", scores.mean(axis=0).round(1))
print("Students above 80 in all subjects:", names[(scores > 80).all(axis=1)])🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
import numpy as np steps = np.array([6500, 9200, 7800, 10400, 5600, 8800, 12000, 4300, 8100, 7600]) print(np.where(steps > 8000)[0])
np.arange(1, 25) into 6 rows × 4 columns and print the sum of each column.Show solution
import numpy as np m = np.arange(1, 25).reshape(6, 4) print(m.sum(axis=0))
Show solution
import numpy as np scores = np.array([[78, 82, 69], [92, 98, 95], [35, 41, 28]]) scores[:, 1] = np.minimum(scores[:, 1] + 5, 100) print(scores)
Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
Why is NumPy faster than Python lists?
Arrays store one data type in contiguous memory, operations run in optimised C loops (vectorisation) without Python overhead per element, and they use CPU features like SIMD.
What does axis=0 vs axis=1 mean?
axis=0 works down the rows and gives one result per column; axis=1 works across columns and gives one result per row.
Summary
- NumPy arrays are fast, typed, n-dimensional containers.
- shape = (rows, cols); index with [row, col]; slice with :.
- Boolean masks filter data without loops.
- reshape, vstack and hstack rearrange data.
Day 9: maths on whole arrays, broadcasting rules, aggregation and random numbers for simulations.
