Vectorisation
Not met yet
Arithmetic and comparisons on an array happen to every item at once, with no loop: marks / 20 * 100 turns every mark into a percentage, and marks == 0 gives an array of True and False. Functions like np.abs work the same way, and .sum() on a True/False array counts the Trues. It is shorter, and far faster, because the work runs as compiled code over numbers of one type stored side by side, instead of Python handling each number in turn.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks arithmetic on a NumPy array needs a loop, so array * 2 or array > 60 is an error.
- Thinks comparing an array with a number gives a single True or False, rather than one for each item.
- Thinks a NumPy array behaves like a list, so * repeats it and + joins two arrays end to end.
Where it comes up
- NumPy Grade Book
- Census Explorer
- Data Cleaning Pipeline
- Summary Statistics Report
- Statistics Toolkit
- Linear Algebra Lab
- Calculus for ML
- Data Story
- House Price Predictor
- Exam Score Model
- Diabetes Risk Classifier
- Iris and Penguins Classifier
- Loan Approval Tree
- Customer Segmentation
- Handwritten Digit Recogniser
- Paper Reproduction