NumPy · lesson 7 of 13
Parts in this lesson
Aprices * 1.122.1: maths on every element
Bkilos * pricetwo arrays, element by element
Cnp.sqrt(a)a ufunc: a function on every element
Dnp.isinf(a)find the infinities

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 inf and nan that 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.

A loop against one line of array maths. Adding 12% VAT to four prices. On the left, a loop. On the right, the array way: prices * 1.12.45464544pricesprices * 1.12out = []for p in prices: out.append(p * 1.12)
1 of 5 Adding 12% VAT to four prices. On the left, a loop. On the right, the array way: 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.

maths.ipynb
  • 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.sqrt and np.log10 work on every element. NumPy calls functions like these ufuncs, universal functions. There are dozens: np.exp, np.abs, np.log and 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.

revenue.ipynb

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.

per-kilo.ipynb

In plain Python, 0 / 0 stops with a ZeroDivisionError. NumPy doesn't stop. It carries on and leaves a special value in the array:

  • 0/0 gives nan: there's no sensible answer.
  • 1800/0 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

np.array([2, 3, 4]) * np.array([10, 20, 30]) is…
Which loop can’t be rewritten as one line of array maths in this way?
An array of prices per kilo has an inf in it. What most likely happened?

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.

All sources for Simple Data Analysis