Array Maths
Array maths works on every value at once. One line adds a number to a whole row of prices.
Add to every value
One number adds to all three prices. No loop is needed.
import numpy as np
prices = np.array([4.5, 6.0, 12.0])
print(prices + 1.0)
Multiply two arrays
Units times price gives the money for each order. Values pair up by position.
import numpy as np
units = np.array([2, 1, 3])
prices = np.array([4.5, 6.0, 12.0])
print(units * prices)
Broadcasting a row
A short row stretches across each row of the grid. Broadcasting is that stretching.
import numpy as np
row = np.array([1, 2, 3])
grid = np.array([[10, 20, 30], [40, 50, 60]])
print(grid + row)
Example
import io
import numpy as np
import pandas as pd
SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
units = np.array(list(sales["units"]))
prices = np.array(list(sales["price"]))
revenue = units * prices
print(revenue)
print(revenue.sum())
Key points
- A single value works on every value in an array at once.
- Two arrays combine value by value, in matching positions.
- Broadcasting stretches a small array across a bigger one.
- Use + to add, * to multiply, and / to divide.
- The result of array maths is a new array.
In this example, the sales table loads from its CSV text. Units and prices each become an array. Multiplying them gives the money for each of the twelve orders. sum adds those twelve amounts to 221.5.
Note
Two arrays must have matching lengths to combine, unless one side stretches.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does np.array([2, 4]) + 10 print?