CHAPTER 07
Beginner
NumPy Broadcasting and Vectorization
Updated: May 18, 2026
5 min read
# CHAPTER 7
NumPy Broadcasting and Vectorization
1. Chapter Introduction
Broadcasting is NumPy's mechanism for performing arithmetic on arrays of different shapes. Vectorization eliminates Python loops — making code 100-1000x faster. These are the two most important performance concepts in NumPy.2. Vectorization vs Python Loops
python
3. Broadcasting Rules
text
4. Broadcasting Examples
python
5. Practical Vectorization Patterns
python
6. Mini Project: Salary Calculator System
python
7. Common Mistakes
-
Broadcasting incompatibility:
(3, 4) + (3, 3)fails. Shapes must be compatible dimension by dimension. Usereshape(-1, 1)to add a dimension.
-
np.wherevs Pythonif:np.where(condition, x, y)is vectorized. Pythonifcannot work on arrays.
8. MCQs
Question 1
NumPy vectorization is faster because?
Question 2
Broadcasting allows?
Question 3
(3,4) + (4,) broadcasting result shape?
Question 4
np.where(cond, x, y) returns?
Question 5
Normalizing data means?
Question 6
(3,1) + (1,4) broadcasts to?
Question 7
np.maximum(a, 0) returns?
Question 8
Typical speedup of NumPy vs Python loop?
Question 9
Z-score normalization formula?
Question 10
reshape(-1, 1) converts 1D array to?
9. Interview Questions
- Q: Explain NumPy broadcasting with an example.
- Q: Why is vectorized code preferred over Python loops in data science?
10. Summary
Vectorization eliminates Python loops — achieving 50-200x speedups. Broadcasting extends scalar/vector operations to match array shapes automatically.np.where provides vectorized conditional logic. These patterns are essential for writing production-quality data science code.