Skip to content
Kuza Ndoto Academy

Array Operations

Beginner → IntermediateChapter 2 · Page 5 of 204 min readUpdated 15 Nov 2026

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
[300 250 400 400] [120 270 100 60] [ 90. 225. 72. 36.]

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)
[[1000 1000 6000] [ 500 750 5000]]

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.

same row reused 10 20 30 5 15 25 × 100 50 200 100 50 200 = 1000 1000 6000 500 750 5000 units (2, 3) price (3,), stretched revenue (2, 3)
Figure 1. Broadcasting: the single price row (gold) is treated as if it were copied down to every row (dashed grey), then multiplied element by element. No real copy is made.

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
105 [15 35 55] [60 45] [20. 15.] [8000 6250]
CallDirectionResult
axis=0Collapses the rows (works down each column)One value per column
axis=1Collapses the columns (works along each row)One value per row
no axisUses every elementA single value
Common mistake

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
[2. 3. 4.] [1.2 5.7] [3 0 2] 117.5 40 250 1

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"))
[ True True False False] 2 [100 250] ['high' 'high' 'low' '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.

Note

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=0 gives one result per column; axis=1 gives one result per row.
  • Comparisons return Boolean arrays you can count or use to filter.
Up next · NumPyIndexing & SlicingSelect the data you need.
→

Tip: use the ← and → keys to move between pages.