PY-73

Apply Corrections along a Named Axis

  • Medium
  • Broadcasting
  • Python

Task

Write apply_axis_corrections(values, corrections, axis).

values is a two-dimensional finite numeric NumPy array. Its rows are observations and its columns are features. corrections is a one-dimensional finite numeric NumPy array. Use the explicit axis names below:

  • axis="columns": corrections[j] is added to every value in column j, so its length must equal the number of columns;
  • axis="rows": corrections[i] is added to every value in row i, so its length must equal the number of rows.

Return a new array with the same shape. The corresponding correction is added to every element, and the input arrays must stay unchanged. Reshape the one-dimensional correction only when its named meaning requires it: a row correction needs shape (rows, 1) before broadcasting, while a column correction already aligns with the final axis.

If axis is not one of the two names, an input is not a two-dimensional or one-dimensional numeric array, a value is not finite, or the correction length does not match its named axis, raise ValueError with "invalid axis correction". In particular, do not silently reshape a wrong-length vector merely to make NumPy accept it.

Example

With axis="columns", the result is [[11, 18, 35], [41, 48, 65]]. With row corrections np.array([100, 200]) and axis="rows", the result is [[110, 120, 130], [240, 250, 260]].

Your implementation

Edit solution.py and keep this function signature:

You may import NumPy as np. The output must have independent storage. Do not modify an input, print, or ask for input.