Skip to content

Commit 83337b6

Browse files
Explain dimension-order alignment with a transposed array
1 parent 54df4e2 commit 83337b6

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

‎fundamentals/02.3_aligning_data_objects.ipynb‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,36 @@
245245
"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"
246246
]
247247
},
248+
{
249+
"cell_type": "markdown",
250+
"metadata": {},
251+
"source": [
252+
"### Dimension order\n",
253+
"\n",
254+
"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."
255+
]
256+
},
257+
{
258+
"cell_type": "code",
259+
"execution_count": null,
260+
"metadata": {},
261+
"outputs": [],
262+
"source": [
263+
"transposed = arr1.transpose(\"time\", \"space\")\n",
264+
"print(arr1.dims, arr1.shape)\n",
265+
"print(transposed.dims, transposed.shape)\n",
266+
"difference = arr1 - transposed\n",
267+
"xr.testing.assert_identical(difference, xr.zeros_like(arr1))\n",
268+
"difference"
269+
]
270+
},
271+
{
272+
"cell_type": "markdown",
273+
"metadata": {},
274+
"source": [
275+
"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."
276+
]
277+
},
248278
{
249279
"cell_type": "markdown",
250280
"metadata": {

0 commit comments

Comments
 (0)