Data Science · Level 1 Arrays

NumPy Broadcasting

Subtract each column's average from a whole table in one line with broadcasting, the trick behind data normalization.

  • A row stretches over every row
  • Shapes are matched from the right
  • Centering data on its mean

When shapes differ, NumPy stretches the smaller array to fit: broadcasting. A row of 3 values applies to every row of an (n, 3) table. Trap: shapes are matched from the right, so a (2,) array can't stretch over (2, 3).

prices = np.array([[10, 20, 30],
                   [12, 22, 32]])
prices - np.array([1, 2, 3])   # each row minus [1, 2, 3]
prices.mean(axis=0)            # array([11., 21., 31.])

Write center(table) that subtracts each column's mean from that column, for example center(np.array([[1, 10], [3, 30]])) gives array([[-1., -10.], [1., 10.]]).

solution.py
Test Suites Pending
Output