Array Operations
Python · NumPy Library
Theory
Arithmetic on arrays is vectorised: + - * / // % and ** work element by element without a loop. price * qty multiplies the first price by the first quantity, the second by the second, and so on, returning a new array of the same shape. An operation with a single number applies it to every element, so rev * 1.18 adds 18% GST to every bill.
Comparisons such as price > 300 also work element-wise and return a boolean array. The two arrays must have the same shape, or shapes that broadcasting can stretch to match; otherwise NumPy raises a ValueError. Division always returns floats, // gives the floor of the division and % the remainder. In-place forms like rev += 10 change the existing array instead of creating a new one.
Why we use it
Element-wise maths replaces loops with one readable line and runs in compiled code, so it is both shorter and much faster. It is how prices, scores and features are transformed in every data pipeline.
When to use it
Use whenever you transform numeric columns: totals, percentages, unit conversions, differences between two readings. If shapes differ, check broadcasting rules; for row or column summaries use aggregations such as sum(axis=...).
How it works
- Two arrays price and qty
- Same shape (or broadcastable)? Yes: Continue. No: ValueError: operands could not be broadcast.
- NumPy pairs element i of price with element i of qty
- Compiled loop applies the operator to every pair
- New array of results (or in-place with +=)
Syntax
a + b a - b a * b a / b a // b a % b a ** 2
a * 1.18 a > 300 a += 10Example
price = np.array([250, 1200, 80])
qty = np.array([4, 1, 10])
print(price * qty) # [1000 1200 800]Key points
- Operators work position by position on equal-shaped arrays
- A scalar is applied to every element
- / returns floats; // floors; % gives the remainder
- Comparisons return boolean arrays you can use as masks
- Mismatched shapes raise ValueError unless they broadcast