# Vectorised Maths and Broadcasting — NumPy / Pandas / scikit-learn

Source: https://www.skillbyai.com/en/numpy-pandas-sklearn/a-broadcast

> Operate on whole arrays.

## Shapes stretch to match

Arithmetic on arrays works **element-wise**. **Broadcasting** lets arrays of different shapes combine: dimensions are compared from the right and must be equal or 1, and size-1 dimensions are stretched virtually without copying. A scalar works with any array; a (3,) vector works with each row of a (2, 3) matrix. Reductions take an `axis`: `axis=0` collapses rows (one result per column), `axis=1` collapses columns (one result per row).

## Tax, order totals and standardisation, run

I ran this with Python 3.12.3 and NumPy 2.5.3. Prices are multiplied by 1.18, a quantity matrix is multiplied row-wise by prices and summed per order, each column is standardised, and incompatible shapes raise a ValueError.

```python
import numpy as np

prices = np.array([100.0, 250.0, 40.0])
print(prices * 1.18)                       # scalar broadcast to every element

qty = np.array([[1, 2, 0],
                [3, 0, 1]])                # 2 orders x 3 products
print(qty * prices)                        # (2,3) * (3,) -> row-wise
print((qty * prices).sum(axis=1))          # total per order

x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
z = (x - x.mean(axis=0)) / x.std(axis=0)   # standardise each column
print(z.round(3))
try:
    np.ones((2, 3)) + np.ones((2,))
except ValueError as e:
    print("ValueError:", e)
```

Output:

```
[118.  295.   47.2]
[[100. 500.   0.]
 [300.   0.  40.]]
[600. 340.]
[[-1.225 -1.225]
 [ 0.     0.   ]
 [ 1.225  1.225]]
ValueError: operands could not be broadcast together with shapes (2,3) (2,) 
```

## Check shapes when results look odd

Print .shape before combining arrays; most surprising results come from an axis you did not intend to broadcast.

**Quiz:** Can a (2, 3) array be added to a (3,) array?

- [x] Yes, the (3,) array is broadcast across each row
- [ ] No, shapes must be identical
- [ ] Only if both are float
- [ ] Only with a loop

*Answer:* Yes, the (3,) array is broadcast across each row. Trailing dimensions match.
