Skip to content

Commit ef6e6a7

Browse files
keewisdcherian
andauthored
raise an error when renaming dimensions to existing names (#3645)
* check we raise an error if the name already exists * raise if the new name already exists and point to swap_dims * update the documentation * whats-new.rst * fix the docstring of rename_dims Co-Authored-By: Deepak Cherian <[email protected]>
1 parent 080caf4 commit ef6e6a7

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/whats-new.rst

+3
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ Bug fixes
6565
By `Tom Augspurger <https://github.com/TomAugspurger>`_.
6666
- Ensure :py:meth:`Dataset.quantile`, :py:meth:`DataArray.quantile` issue the correct error
6767
when ``q`` is out of bounds (:issue:`3634`) by `Mathias Hauser <https://github.com/mathause>`_.
68+
- Raise an error when trying to use :py:meth:`Dataset.rename_dims` to
69+
rename to an existing name (:issue:`3438`, :pull:`3645`)
70+
By `Justus Magin <https://github.com/keewis>`_.
6871
- :py:meth:`Dataset.rename`, :py:meth:`DataArray.rename` now check for conflicts with
6972
MultiIndex level names.
7073

xarray/core/dataset.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -2798,7 +2798,8 @@ def rename_dims(
27982798
----------
27992799
dims_dict : dict-like, optional
28002800
Dictionary whose keys are current dimension names and
2801-
whose values are the desired names.
2801+
whose values are the desired names. The desired names must
2802+
not be the name of an existing dimension or Variable in the Dataset.
28022803
**dims, optional
28032804
Keyword form of ``dims_dict``.
28042805
One of dims_dict or dims must be provided.
@@ -2816,12 +2817,17 @@ def rename_dims(
28162817
DataArray.rename
28172818
"""
28182819
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
2819-
for k in dims_dict:
2820+
for k, v in dims_dict.items():
28202821
if k not in self.dims:
28212822
raise ValueError(
28222823
"cannot rename %r because it is not a "
28232824
"dimension in this dataset" % k
28242825
)
2826+
if v in self.dims or v in self:
2827+
raise ValueError(
2828+
f"Cannot rename {k} to {v} because {v} already exists. "
2829+
"Try using swap_dims instead."
2830+
)
28252831

28262832
variables, coord_names, sizes, indexes = self._rename_all(
28272833
name_dict={}, dims_dict=dims_dict

xarray/tests/test_dataset.py

+3
Original file line numberDiff line numberDiff line change
@@ -2444,6 +2444,9 @@ def test_rename_dims(self):
24442444
with pytest.raises(ValueError):
24452445
original.rename_dims(dims_dict_bad)
24462446

2447+
with pytest.raises(ValueError):
2448+
original.rename_dims({"x": "z"})
2449+
24472450
def test_rename_vars(self):
24482451
original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})
24492452
expected = Dataset(

0 commit comments

Comments
 (0)