xarray
xarray copied to clipboard
Fix DataArray coordinate mismatch after shape-changing array wrap
Summary
- Route
DataArray.__array_wrap__through_replace_maybe_drop_dimsto 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.pinvon 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):
Variable.__array_wrap__detects the shape changed from(3, 4)to(4, 3)— the last two dims are transposed- It returns a new Variable with swapped dims:
(bar, foo) 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