Vectorised maths and ufuncs
Last updated
In lesson 2.1 you added VAT to every price with one multiplication. That's called vectorised code, and it's how you'll do nearly all maths on data from now on. In this lesson you'll meet NumPy's maths functions, rewrite a loop as one line, and see what happens when you divide by zero.
By the end of this lesson you can
- Do arithmetic between an array and a number, and between two arrays
- Use NumPy's maths functions:
round,sqrt,log10,clip - Rewrite a loop over two lists as one line of array maths
- Find the
infandnanthat dividing by zero leaves behind
One line instead of a loop
Here's what a vectorised line does, matched step by step against the loop it replaces.
prices * 1.12.Same multiplications, same answers. The array version is shorter, easier to read and much faster. Writing code this way is called vectorising it.
Maths functions
Run the cells.
- Arithmetic with a number works on every element. Arithmetic between two arrays of the same shape pairs them up: first with first, second with second.
np.round,np.sqrtandnp.log10work on every element. NumPy calls functions like these ufuncs, universal functions. There are dozens:np.exp,np.abs,np.logand more, all listed in the sources.- Comparisons give masks, as in lesson 2.5.
np.clip(a, low, high)keeps every value between two limits: anything below 0 becomes 0, anything above 100 becomes 100. Useful for percentages that came out of a calculation as 102%.
Rewriting a loop
Here's a loop of the kind you wrote in Simple Python: kilos times price for each day, collected into a list. Run both cells.
The loop needs four lines, an empty list and zip. The array version is one line, and says what it means: kilos times price.
To vectorise a loop, look for the line inside it that does the work (k * p), and write that line with whole arrays instead of single values (kilos * price). It works whenever each step of the loop doesn't depend on the step before.
Wrong way: dividing by zero
Lipa was closed on Tuesday, so it sold 0 kg and took ₱0. You work out each store's price per kilo. Run the cells.
In plain Python, 0 / 0 stops with a ZeroDivisionError. NumPy doesn't stop. It carries on and leaves a special value in the array:
- gives
nan: there's no sensible answer. - gives
inf, infinity.
On your own computer, NumPy also prints a RuntimeWarning under the cell (divide by zero encountered or invalid value encountered). The Python in this page can't detect those, so it shows no warning at all, but the nan is there just the same. And warnings are easy to miss: in a notebook with 40 cells you scroll straight past them. Either way, the nan and inf go on into every total and average you work out from this array.
So check, as the third cell does: count the nans and infs with np.isnan and np.isinf. Then decide what the answer should be. The last cell uses np.divide with where=kilos > 0: it only divides where kilos isn't zero, and puts 0 (from out=np.zeros(3)) everywhere else. Whether 0 is right, or the day should be left out, is a question about the data, not about code.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- NumPy: Universal functions (ufunc) basics: functions that work element by element
- NumPy: Mathematical functions: the full list: sqrt, log10, round, clip and more
- NumPy: numpy.divide: the where and out arguments
- NumPy: Floating point error handling: the warnings for dividing by zero