pydata / pydata/xarray

align skips alignment checks for indexes that are not reindexed

Open
#10,714 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-indexing
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

What happened?

When aligning two Datasets, indexes that are already aligned (require no reindexing) are not considered when checking for index conflicts.

More concretely:
When I attempt to align two Datasets that share two indexes for the same dimension of which one is aligned (requires no reindexing) and the other is not, no error is raised if these indexes conflict with one another. The mismatched index is used to align the data.

What did you expect to happen?

I would expect an AlignmentError to be raised when an attempt is made to align objects with conflicting indexes in all situations.

Minimal Complete Verifiable Example
from xarray import align, Dataset
ds1 = Dataset(coords={"x": [1, 2, 3], "xb": ("x", [4, 5, 6])}).set_xindex("xb")
# Swap two values in only "xb" only
ds2 = Dataset(coords={"x": [1, 2, 3], "xb": ("x", [4, 6, 5])}).set_xindex("xb")
# Swap two (different) values in both coordinates
ds3 = Dataset(coords={"x": [2, 1, 3], "xb": ("x", [4, 6, 5])}).set_xindex("xb")

align(ds1, ds2)  # --> no error       (which is wrong)
align(ds1, ds3)  # --> AlignmentError (as expected)

MVCE confirmation
  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.
  • Recent environment — the issue occurs with the latest version of xarray and its dependencies.
Relevant log output

Anything else we need to know?

Until recently, alignment it was not possible when multiple indexes shared a dimension. This functionality was introduced in xarray v2025.04.0 and originally merged in PR https://github.com/pydata/xarray/issues/8436 by @benbovy .

The problem is that the index consistency checks ignore indexes that require no reindexing.

# Source: xarray/structure/alignment.py

    def _get_dim_pos_indexers(
        self,
        matching_indexes: dict[MatchingIndexKey, Index],
    ) -> dict[Hashable, Any]:
        dim_pos_indexers: dict[Hashable, Any] = {}
        dim_index: dict[Hashable, Index] = {}

        for key, aligned_idx in self.aligned_indexes.items():
            obj_idx = matching_indexes.get(key)
            if obj_idx is not None and self.reindex[key]:
                #######################################################################
                # ↓ None of this code is run for indexes that require no reindexing ↓ #
                #######################################################################
                indexers = obj_idx.reindex_like(aligned_idx, **self.reindex_kwargs)
                for dim, idxer in indexers.items():
                    if dim in self.exclude_dims:
                        raise AlignmentError(
                            f"cannot reindex or align along dimension {dim!r} because "
                            "it is explicitly excluded from alignment. This is likely caused by "
                            "wrong results returned by the `reindex_like` method of this index:\n"
                            f"{obj_idx!r}"
                        )
                    if dim in dim_pos_indexers and not np.array_equal(
                        idxer, dim_pos_indexers[dim]
                    ):
                        raise AlignmentError(
                            f"cannot reindex or align along dimension {dim!r} because "
                            "of conflicting re-indexers returned by multiple indexes\n"
                            f"first index: {obj_idx!r}\nsecond index: {dim_index[dim]!r}\n"
                        )
                    dim_pos_indexers[dim] = idxer
                    dim_index[dim] = obj_idx

        return dim_pos_indexers
Environment
INSTALLED VERSIONS ------------------ commit: None python: 3.13.2 (main, Mar 11 2025, 17:20:07) [MSC v.1943 64 bit (AMD64)] python-bits: 64 OS: Windows OS-release: 11 machine: AMD64 processor: Intel64 Family 6 Model 142 Stepping 12, GenuineIntel byteorder: little LC_ALL: None LANG: None LOCALE: ('English_United States', '1252') libhdf5: None libnetcdf: None

xarray: 2025.9.0
pandas: 2.3.2
numpy: 2.3.2
scipy: None
netCDF4: None
pydap: None
h5netcdf: None
h5py: None
zarr: None
cftime: None
nc_time_axis: None
iris: None
bottleneck: None
dask: None
distributed: None
matplotlib: None
cartopy: None
seaborn: None
numbagg: None
fsspec: None
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: None
pip: None
conda: None
pytest: None
mypy: None
IPython: 9.5.0
sphinx: None

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in xarray/structure/alignment.py at _get_dim_pos_indexers and run the provided minimal example to observe the differing behavior for ds1/ds2 and ds1/ds3. Trace how aligned and reindexed indexes are checked. Done means conflicting indexes consistently raise AlignmentError, including when one index requires no reindexing.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
data
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.