From 4c05d38459dcf20ac4dc7fb32bb8cef4d7627c8b Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Fri, 11 Oct 2019 08:47:57 -0700 Subject: [PATCH] BUG: overrides to a dimension coordinate do not get aligned (#3393) Fixes GH3377 --- xarray/core/alignment.py | 8 +++++++- xarray/tests/test_dataset.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/xarray/core/alignment.py b/xarray/core/alignment.py index b4fee1773b8..a905dd37b35 100644 --- a/xarray/core/alignment.py +++ b/xarray/core/alignment.py @@ -374,7 +374,13 @@ def is_alignable(obj): elif is_dict_like(variables): current_out = OrderedDict() for k, v in variables.items(): - if is_alignable(v): + if is_alignable(v) and k not in indexes: + # Skip variables in indexes for alignment, because these + # should to be overwritten instead: + # https://github.com/pydata/xarray/issues/725 + # https://github.com/pydata/xarray/issues/3377 + # TODO(shoyer): doing this here feels super-hacky -- can we + # move it explicitly into merge instead? positions.append(position) keys.append(k) targets.append(v) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index fdd5a419383..e9efd5e7254 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -3047,6 +3047,21 @@ def test_setitem_auto_align(self): expected = Dataset({"x": ("y", [4, 5, 6])}, {"y": range(3)}) assert_identical(ds, expected) + def test_setitem_dimension_override(self): + # regression test for GH-3377 + ds = xr.Dataset({"x": [0, 1, 2]}) + ds["x"] = ds["x"][:2] + expected = Dataset({"x": [0, 1]}) + assert_identical(ds, expected) + + ds = xr.Dataset({"x": [0, 1, 2]}) + ds["x"] = np.array([0, 1]) + assert_identical(ds, expected) + + ds = xr.Dataset({"x": [0, 1, 2]}) + ds.coords["x"] = [0, 1] + assert_identical(ds, expected) + def test_setitem_with_coords(self): # Regression test for GH:2068 ds = create_test_data()