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()