xarray icon indicating copy to clipboard operation
xarray copied to clipboard

Fix DataArray coordinate mismatch after shape-changing array wrap

Open C1-BA-B1-F3 opened this issue 5 months ago • 0 comments

Summary

  • Route DataArray.__array_wrap__ through _replace_maybe_drop_dims to properly handle coordinates when shape changes
  • In Variable.__array_wrap__, detect when the last two dims are transposed (e.g. np.linalg.pinv) and swap dim names accordingly
  • Fall back to generic dim names for other shape changes where dims can't be reliably mapped
  • Add a regression test for np.linalg.pinv on a rectangular DataArray

Fixes #11396

How it works

When np.linalg.pinv is called on a DataArray of shape (3, 4) with dims (foo, bar):

  1. Variable.__array_wrap__ detects the shape changed from (3, 4) to (4, 3) — the last two dims are transposed
  2. It returns a new Variable with swapped dims: (bar, foo)
  3. DataArray.__array_wrap__ calls _replace_maybe_drop_dims, which sees that sizes match after the dim swap and preserves all coordinates

This approach correctly maps dimensions rather than just dropping mismatched coordinates, so coords like foo: ['x', 'y', 'z'] stay on the foo dimension (which is still size 3).

Tests

python3 -m pytest -o addopts='' xarray/tests/test_dataarray.py::TestDataArray::test_array_wrap_drops_mismatched_coords
python3 -m pytest -o addopts='' xarray/tests/test_dataarray.py::TestDataArray::test_array_interface xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keepdims xarray/tests/test_dataarray.py::TestDataArray::test_math_with_coords
python3 -m pytest -o addopts='' xarray/tests/test_computation.py::test_apply_dask_new_output_sizes_not_supplied_same_dim_names
python3 -m pytest -o addopts='' xarray/tests/test_variable.py

🤖 Generated with Claude Code

C1-BA-B1-F3 avatar Jun 25 '26 20:06 C1-BA-B1-F3