Sub topic 2
Vectorizing Arithmetic and Conditions
Assume you know how to select pandas columns, use groupby, and work with NumPy arrays. This chapter focuses on replacing Python-level row processing with operations over complete columns.
Vectorize column operations
Vectorization applies one operation to an entire Series or DataFrame. Pandas and NumPy can perform much of this work in compiled code, avoiding a Python function call for every row.
import numpy as np
import pandas as pd
sales = pd.DataFrame({
"price": [10.0, 25.0, 8.0],
"qty": [2, 5, 10],
})
sales["total"] = sales["price"] * sales["qty"]
sales["discount"] = np.where(sales["qty"] >= 5, 0.10, 0.0)
sales["net"] = sales["total"] * (1 - sales["discount"])
print(sales)np.where(condition, value_if_true, value_if_false) evaluates a condition for the whole column. For several conditions, use boolean masks or np.select.
flowchart TD
A[Input columns] --> B[Column-wise arithmetic]
B --> C[Boolean condition]
C --> D[Updated DataFrame]Prove the result is unchanged
Optimization is safe only when the new result matches the old result. Keep a small reference implementation while rewriting the code, then compare values, indexes, and dtypes.
import pandas as pd
slow = sales["total"].apply(lambda value: value * 1.2)
fast = sales["total"] * 1.2
pd.testing.assert_series_equal(slow, fast)For floating-point calculations, use assert_series_equal(..., check_exact=False, rtol=..., atol=...) when tiny rounding differences are expected. Test empty input, missing values, and boundary conditions such as qty == 5.
When row-wise tools are appropriate
apply is reasonable when each value needs a genuinely custom function that has no vectorized equivalent. Series.map works well for dictionary lookups or simple value-to-value mappings. Pandas string methods, such as .str.lower() and .str.contains(), are usually preferable to a Python loop over strings.
These tools can still be slower than built-in arithmetic. Measure before and after, and do not replace clear code merely because it uses apply.
Exercise
What should you use instead of apply(axis=1) to calculate price * qty and assign a discount when qty >= 5?
Show answer
Multiply the two Series directly and use np.where for the condition.