NumPy Arrays and Vectorization
Create NumPy arrays, understand shape and dtype, and replace slow Python loops with vectorized operations that run on whole arrays at once.
Welcome back!
Step 1 of 13Learn
One line instead of a loop
A store has the prices of 2 million products and needs to apply an 8% increase. In plain Python:
new_prices = []
for p in prices:
new_prices.append(p * 1.08)With NumPy:
import numpy as np
prices = np.array(prices)
new_prices = prices * 1.08The NumPy version is shorter, and typically tens to hundreds of times faster. Writing operations on whole arrays instead of individual elements is called vectorization, and it's the central habit of numeric Python.
The core object is the ndarray (n-dimensional array): a grid of values, all of the same type, stored in one contiguous block of memory. Ways to create one:
np.array([3, 1, 4, 1, 5]) # from a list
np.zeros(5) # [0. 0. 0. 0. 0.]
np.ones((2, 3)) # 2 rows, 3 columns of 1.0
np.arange(0, 10, 2) # [0 2 4 6 8] (end excluded)
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ] (end included)Arithmetic between arrays of the same shape works element by element: np.array([1, 2, 3]) + np.array([10, 20, 30]) gives [11 22 33]. Compare that with Python lists, where [1, 2, 3] + [10, 20, 30] concatenates into a six-item list. That difference catches many newcomers.
Step 2 of 13Practice · What would you do?
What would you do?
What does each line produce?
a = [1, 2, 3]
b = np.array([1, 2, 3])
print(a * 2)
print(b * 2)Step 3 of 13Learn
Shape, dimensions and dtype
Every array has a few attributes you'll check constantly:
m = np.array([[1, 2, 3],
[4, 5, 6]])
m.ndim # 2 number of dimensions (axes)
m.shape # (2, 3) 2 rows, 3 columns
m.size # 6 total number of elements
m.dtype # int64 type of every element (platform-dependent)The shape is a tuple with one number per dimension. A 1-D array of 5 values has shape (5,), with the trailing comma marking a one-element tuple. A 2-D table of 1,000 rows and 4 columns has shape (1000, 4). A batch of 32 color images of 64 × 64 pixels has shape (32, 64, 64, 3).
The dtype says what every element is: int64, float64, bool, and so on. Because all elements share one type, mixing types forces a conversion: np.array([1, 2.5]) becomes float64, and np.array([1, "a"]) turns everything into strings, which silently breaks arithmetic.
You can reshape an array as long as the total size stays the same:
np.arange(12).reshape(3, 4) # 3 rows of 4
np.arange(12).reshape(2, -1) # -1 means "work it out": 2 rows of 6Reshaping 12 elements into (5, 3) fails, because 5 × 3 = 15 ≠ 12.
Step 4 of 13Practice · Work it out
An array holds daily temperature readings for 52 weeks, 7 days per week, with 24 hourly readings per day, stored with shape (52, 7, 24). What is its size (total number of elements)?
Step 5 of 13Practice · Choose one
What is the dtype of np.array([3, 7, 2.5, 10])?
Step 6 of 13Learn
Universal functions and min-max scaling
NumPy provides universal functions (ufuncs) that apply element-wise across arrays at C speed: np.sqrt, np.exp, np.log, np.abs, np.round and many more. Combined with array arithmetic, they let you express formulas almost exactly as written on paper.
A common data science example is min-max scaling, which rescales values to the range 0 to 1:
scaled = (x − min) / (max − min)
x = np.array([20, 35, 50, 80])
scaled = (x - x.min()) / (x.max() - x.min())
# array([0. , 0.25, 0.5 , 1. ])Each piece is vectorized: x - x.min() subtracts 20 from every element, and the division happens element by element too. Scaling matters because many machine learning methods compare features on different scales, such as income in dollars and age in years, and the large-valued feature would otherwise dominate.
Two more frequent operations:
- Standardization (z-scores):
(x - x.mean()) / x.std()gives values with mean 0 and standard deviation 1. - Logs:
np.log(x)compresses heavily skewed data such as incomes or populations. Watch out:np.log(0)is-infand negatives givenan, with only a warning, not an error.
Step 7 of 13Practice · Code challenge · Python
NumPy isn't available in this sandbox, so implement the idea in plain Python. Write min_max_scale(values) that returns a new list where each value is rescaled with (x − min) / (max − min), rounded to 3 decimal places. If all values are equal, return a list of zeros of the same length.
min_max_scale([20, 35, 50, 80])min_max_scale([3, 1, 2])min_max_scale([5, 5, 5])min_max_scale([0, 1, 2, 10])
Step 8 of 13Explore
Min-max scaling
The line maps an original value x to its scaled value. Move the minimum and maximum of the data and watch the mapping change. Values outside the original range land below 0 or above 1.
- Scaled value of 50
- 0.5
- Original value that maps to 0.5
- 50
Step 9 of 13Learn
Random numbers and reproducibility
Data science uses random numbers constantly: shuffling data, splitting it into training and test sets, sampling, simulating scenarios and initializing models. NumPy's modern interface is a random generator object:
rng = np.random.default_rng(seed=42)
rng.integers(1, 7, size=10) # ten dice rolls
rng.normal(loc=70, scale=10, size=1000) # 1,000 values from a normal distribution
rng.choice(["A", "B", "C"], size=5)
rng.permutation(10) # a shuffled 0..9The seed matters. Computers generate pseudo-random numbers from a starting value; the same seed produces the same sequence every time. That makes analyses reproducible: a colleague rerunning your notebook gets the same sample, the same split and the same results. Without a seed, every run differs slightly, which makes debugging and reviewing much harder.
Simulation is a powerful use of vectorized random numbers. To estimate how often a station with 20 bikes runs out when demand averages 16 with some variation, you can simulate 100,000 mornings in one line and count the shortages, instead of deriving a formula.
One caution: the seed is for reproducibility, not for picking a "good" result. Trying seeds until the numbers look nice is a subtle way of fooling yourself.
Step 10 of 13Practice · True or false
Creating a generator with the same seed, such as np.random.default_rng(42), produces the same sequence of random numbers each time the code runs.
Step 11 of 13Note
Step 12 of 13Note
Step 13 of 13Practice · True or false
np.arange(0, 10, 2) includes the end value 10, giving [0 2 4 6 8 10].
Lesson complete!