From 6b4adf40a45e464b6ff03fd37e5c80a6a776c6a6 Mon Sep 17 00:00:00 2001 From: "gupta.harshit@zomato.com" Date: Sun, 23 Nov 2025 21:01:55 +0000 Subject: [PATCH] Fix combine_by_coords monotonicity check for non-concat dims Only require monotonic coordinates along concatenation dimensions. Previously, identical non-monotonic coordinates on non-concat dims erroneously raised a ValueError. Includes regression test. Closes # (refer to issue number if applicable) --- xarray/core/combine.py | 3 ++- xarray/tests/test_combine.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/xarray/core/combine.py b/xarray/core/combine.py index 37ae903b6c3..5f5be49c83b 100644 --- a/xarray/core/combine.py +++ b/xarray/core/combine.py @@ -501,7 +501,8 @@ def combine_by_coords(datasets, compat='no_conflicts', data_vars='all', fill_value=fill_value) # Check the overall coordinates are monotonically increasing - for dim in concatenated.dims: + # Only check dimensions that were used for concatenation + for dim in concat_dims: if dim in concatenated: indexes = concatenated.indexes.get(dim) if not (indexes.is_monotonic_increasing diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index 77e2993b7fd..b8ec93cdc66 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -618,6 +618,30 @@ def test_check_for_impossible_ordering(self): " along dimension x"): combine_by_coords([ds1, ds0]) + def test_combine_by_coords_non_monotonic_non_concat_dim(self): + # Test that non-monotonic coordinates are allowed on dimensions + # that don't vary between datasets (i.e., not concatenation dims) + # Regression test for GH issue + yCoord = ['a', 'c', 'b'] # non-monotonic + + ds1 = Dataset( + data_vars={'data': (['x', 'y'], np.random.rand(3, 3))}, + coords={'x': [1, 2, 3], 'y': yCoord} + ) + + ds2 = Dataset( + data_vars={'data': (['x', 'y'], np.random.rand(4, 3))}, + coords={'x': [4, 5, 6, 7], 'y': yCoord} + ) + + # Should not raise an error - y is not a concatenation dimension + actual = combine_by_coords([ds1, ds2]) + + # Verify the result has the expected shape and coordinates + assert actual.dims == {'x': 7, 'y': 3} + assert list(actual.coords['x'].values) == [1, 2, 3, 4, 5, 6, 7] + assert list(actual.coords['y'].values) == yCoord + @pytest.mark.filterwarnings("ignore:In xarray version 0.13 `auto_combine` " "will be deprecated")