Array Operations
The real power of NumPy is that you can do maths on a whole array in one go, with no loops. This is called vectorisation, and it makes your code shorter, clearer and much faster.
Element-wise arithmetic
Arithmetic between two arrays of the same shape works element by element: the first item with the first item, the second with the second, and so on.
import numpy as np prices = np.array([100, 250, 80, 40]) # KES per item qty = np.array([3, 1, 5, 10]) # items sold print(prices * qty) # revenue per product print(prices + 20) # a KES 20 price rise print(prices * 0.9) # a 10% discount
In prices + 20, the single number 20 is applied to every element. Multiplying by 0.9 turns the result into floats, which NumPy prints with a trailing dot. All the usual operators work: +, -, *, /, //, % and **.
Compare this with plain Python, where you would need a loop or a comprehension: [p * q for p, q in zip(prices, qty)]. The NumPy version is shorter and, for large arrays, far faster.
Broadcasting
Broadcasting is NumPy's rule for combining arrays of different shapes. The smaller array is "stretched" to match the larger one, without actually copying data. Here, two branches sold three products, and one price list applies to both branches:
units = np.array([[10, 20, 30], # branch A
[ 5, 15, 25]]) # branch B
price = np.array([100, 50, 200]) # one price per product (column)
revenue = units * price
print(revenue)
The price array of shape (3,) was applied to each row of the (2, 3) array. Broadcasting works when, comparing shapes from the right, each pair of sizes is either equal or one of them is 1. Shapes (3,) and (2,) don't fit, so np.array([1, 2, 3]) + np.array([1, 2]) raises ValueError: operands could not be broadcast together.
Aggregations and the axis argument
Aggregation functions reduce many values to one: sum(), mean(), min(), max(), std(). On a 2-D array, the axis argument chooses the direction.
print(units.sum()) # everything print(units.sum(axis=0)) # down the rows: one total per column (product) print(units.sum(axis=1)) # across the columns: one total per row (branch) print(units.mean(axis=1)) # average units per product, per branch print(revenue.sum(axis=1)) # revenue per branch
| Call | Direction | Result |
|---|---|---|
axis=0 | Collapses the rows (works down each column) | One value per column |
axis=1 | Collapses the columns (works along each row) | One value per row |
| no axis | Uses every element | A single value |
Axis confusion is one of the most common bugs in data work. Remember: the axis you name is the one that disappears. axis=0 squashes the rows away, leaving one answer per column. pandas uses the same rule, so df.sum(axis=0) gives column totals while df.drop("notes", axis=1) removes a column. If in doubt, check the result's shape.
Universal functions (ufuncs)
NumPy provides maths functions that work on every element at once:
print(np.sqrt(np.array([4, 9, 16]))) print(np.round(np.array([1.234, 5.678]), 1)) print(np.abs(np.array([-3, 0, 2]))) print(prices.mean(), prices.min(), prices.max()) print(prices.argmax()) # position of the largest value
Other useful ufuncs include np.log(), np.exp(), np.maximum() and np.cumsum() (a running total).
Comparisons create Boolean arrays
Comparing an array with a value gives an array of True/False. This is the basis of filtering data.
expensive = prices > 90 print(expensive) print(expensive.sum()) # True counts as 1 print(prices[expensive]) # keep only the True positions print(np.where(prices > 90, "high", "low"))
np.where(condition, a, b) picks a where the condition is true and b elsewhere, which is handy for labelling data. You'll see much more of Boolean selection on the next page, Indexing & Slicing.
Printing a single NumPy number with print() shows just the value, for example 117.5. If you type the expression on its own in a notebook, NumPy 2 shows its type too, such as np.float64(117.5). Both are the same number.
Key points
- Arithmetic on arrays is element-wise, so you rarely need loops.
- Broadcasting lets a single value or a smaller array combine with a larger one.
axis=0gives one result per column;axis=1gives one result per row.- Comparisons return Boolean arrays you can count or use to filter.
Tip: use the ← and → keys to move between pages.
