Lecture 13 live coding#
2026-11-03
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=42)
Logical indexing and vectorization#
Let’s briefly explore the benefits of “vectorization” in NumPy and pandas, which is the practice of performing operations on entire arrays at once, rather than element-by-element via a loop.
We’ll compute the numerator of the standardized difference calculation \(d_X\) from Project 2, which is essentially the difference-in-means estimator for covariate \(X\):
Recall that \(\hat{E}[X \mid T=t]\) is the estimated mean of \(X\) given that \(T=t\).
The code cells below start with a %%time magic command, which times the execution of the cell. We’ll use it to compare the performance of looped and vectorized code.
%%time
# short demo of the time magic command
for i in range(1000):
pass
CPU times: user 21 μs, sys: 0 ns, total: 21 μs
Wall time: 21.9 μs
# load in a simulated dataset with 50000 rows and T, X columns
df = pd.read_csv("~/COMSC-341CD/data/vectorized_sim_data.csv")
df.head()
| T | X | |
|---|---|---|
| 0 | 1 | 10.468910 |
| 1 | 0 | 0.250017 |
| 2 | 1 | 10.110894 |
| 3 | 1 | 9.958819 |
| 4 | 1 | 10.287618 |
Version 1: with a loop#
First, let’s compute \(\hat{E}[X \mid T=1] - \hat{E}[X \mid T=0]\) by looping over the rows of the DataFrame.
%%time
T1_sum = 0
T0_sum = 0
# sum up the values of X for each treatment group by iterating over the rows of the DataFrame
# calculate the mean of X for each treatment group
T1_mean = 0
T0_mean = 0
# the difference should be close to 10 for the simulated data
# assert np.isclose(T1_mean - T0_mean, 10, atol=1e-2)
CPU times: user 2 μs, sys: 0 ns, total: 2 μs
Wall time: 3.1 μs
# COMPLETED CELL
# %%time
# T1_sum = 0
# T0_sum = 0
# # sum up the values of X for each treatment group by iterating over the rows of the DataFrame
# # Python note: "_" is a convention for a variable that is not used in the loop
# for _, row in df.iterrows():
# if row['T'] == 1:
# T1_sum += row['X']
# else:
# T0_sum += row['X']
# # calculate the mean of X for each treatment group
# T1_mean = T1_sum / df[df["T"] == 1].shape[0]
# T0_mean = T0_sum / df[df["T"] == 0].shape[0]
# # the difference should be close to 10 for the simulated data
# assert np.isclose(T1_mean - T0_mean, 10, atol=1e-2)
Version 2: vectorized#
Now let’s compute the same quantity with no loops, using logical indexing and the mean() function.
%%time
# no loops: logical indexing to select each treatment group, then mean()
T1_mean = 0
T0_mean = 0
# the difference should be close to 10 for the simulated data
# assert np.isclose(T1_mean - T0_mean, 10, atol=1e-2)
CPU times: user 1 μs, sys: 0 ns, total: 1 μs
Wall time: 2.62 μs
# COMPLETED CELL
# %%time
# # no loops: logical indexing to select each treatment group, then mean()
# T1_mean = df[df['T'] == 1]['X'].mean()
# T0_mean = df[df['T'] == 0]['X'].mean()
# # the difference should be close to 10 for the simulated data
# assert np.isclose(T1_mean - T0_mean, 10, atol=1e-2)
Comparing the wall times of the two cells, the vectorized version is shorter to write and runs orders of magnitude faster than the loop.
Takeaway
If you’re writing code processing NumPy arrays or pandas DataFrames and you find yourself writing a loop over the length of an array or DataFrame, try to think about whether you can vectorize the operation. Unless the operation explicitly calls for iterating over the rows in a DataFrame (like we do in implementing greedy pair matching for Project 2), it is likely that you can achieve the same result without the loop, resulting in both faster and more concise code.