From 83337b64f75a295bec1e6fa7955a5f0f7dbbcbc6 Mon Sep 17 00:00:00 2001 From: Himanshu Agrawal Date: Fri, 6 Nov 2026 00:53:29 +0530 Subject: [PATCH] Explain dimension-order alignment with a transposed array --- fundamentals/02.3_aligning_data_objects.ipynb | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/fundamentals/02.3_aligning_data_objects.ipynb b/fundamentals/02.3_aligning_data_objects.ipynb index 490fbc88..ea8cc26f 100644 --- a/fundamentals/02.3_aligning_data_objects.ipynb +++ b/fundamentals/02.3_aligning_data_objects.ipynb @@ -245,6 +245,36 @@ "For more, see the [Xarray documentation](https://docs.xarray.dev/en/stable/user-guide/computation.html#broadcasting-by-dimension-name) and the [numpy documentation](https://numpy.org/doc/stable/user/basics.broadcasting.html) on broadcasting.\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Dimension order\n", + "\n", + "Dimensions are matched by name even when they appear in a different order. Transposing `arr1` changes its shape from `(3, 4)` to `(4, 3)`, but each value still has the same `space` and `time` labels. Subtracting the transposed array therefore gives zero at every location, without reshaping either input." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "transposed = arr1.transpose(\"time\", \"space\")\n", + "print(arr1.dims, arr1.shape)\n", + "print(transposed.dims, transposed.shape)\n", + "difference = arr1 - transposed\n", + "xr.testing.assert_identical(difference, xr.zeros_like(arr1))\n", + "difference" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The values align by name, but the result still has an ordered set of dimensions: dimensions appear in the order they first occur in the inputs. Here `difference.dims` is `('space', 'time')`. Use `.transpose(...)` when you need a particular axis order, especially before passing `.data` to NumPy or another positional array API." + ] + }, { "cell_type": "markdown", "metadata": {