xarray icon indicating copy to clipboard operation
xarray copied to clipboard

Harmonize returned multi-indexed indexes when applying `concat` along new dimension

Open FabianHofmann opened this issue 1 year ago • 2 comments

  • [x] Closes #6881
  • [x] Tests added

In the current implementation, the concat function does not ensure that the indexes that belong to the same MultiIndex relate to the same MultiIndex object in Dataset.indexes when concatenating along a new dimension. This becomes a problem as soon as the returned dataset needs to be aligned (for broadcasting, reindexing etc.), see #6881 for example. As far as I understand, this bug was introduced in https://github.com/pydata/xarray/pull/5692 following the idea that the concat function should disentangle indexes and dimensions.

It can be fixed by not removing the index name from the list of indexes which should be merged, see https://github.com/pydata/xarray/blob/9050a8b9efc28142b762475c7285603a87b00e83/xarray/core/concat.py#L493. All indexes contained in this list will get a new index object. Currently, this list only contains the levels of a multi-indexed index, not the index name itself. This is removed as it is contained in dim_names. Instead of removing all dimension names from this list, I suggest to only remove unlabeled dimensions from this list.

FabianHofmann avatar Aug 08 '22 13:08 FabianHofmann

Thanks @benbovy¸ glad that the proposed fix can help here!

FabianHofmann avatar Aug 11 '22 09:08 FabianHofmann

@benbovy I applied your suggestion (+ a small fix) and merged with the up to date main branch. All tests pass.

FabianHofmann avatar Aug 15 '22 10:08 FabianHofmann

LGTM, thanks @FabianHofmann! Could you update whats-new.rst in the docs? I think this bug fix is worth to be mentioned there with your contribution.

benbovy avatar Aug 23 '22 10:08 benbovy

@benbovy done :)

FabianHofmann avatar Aug 25 '22 09:08 FabianHofmann

All good, thanks @FabianHofmann !

benbovy avatar Aug 25 '22 11:08 benbovy

Great, thanks for the nice review @benbovy

FabianHofmann avatar Aug 25 '22 14:08 FabianHofmann