Skip to content

Commit

Permalink
raise an error when renaming dimensions to existing names (#3645)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
keewis and dcherian committed Jan 9, 2020
1 parent 080caf4 commit ef6e6a7
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ Bug fixes
By `Tom Augspurger <https://github.com/TomAugspurger>`_.
- Ensure :py:meth:`Dataset.quantile`, :py:meth:`DataArray.quantile` issue the correct error
when ``q`` is out of bounds (:issue:`3634`) by `Mathias Hauser <https://github.com/mathause>`_.
- Raise an error when trying to use :py:meth:`Dataset.rename_dims` to
rename to an existing name (:issue:`3438`, :pull:`3645`)
By `Justus Magin <https://github.com/keewis>`_.
- :py:meth:`Dataset.rename`, :py:meth:`DataArray.rename` now check for conflicts with
MultiIndex level names.

Expand Down
10 changes: 8 additions & 2 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2798,7 +2798,8 @@ def rename_dims(
----------
dims_dict : dict-like, optional
Dictionary whose keys are current dimension names and
whose values are the desired names.
whose values are the desired names. The desired names must
not be the name of an existing dimension or Variable in the Dataset.
**dims, optional
Keyword form of ``dims_dict``.
One of dims_dict or dims must be provided.
Expand All @@ -2816,12 +2817,17 @@ def rename_dims(
DataArray.rename
"""
dims_dict = either_dict_or_kwargs(dims_dict, dims, "rename_dims")
for k in dims_dict:
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
"cannot rename %r because it is not a "
"dimension in this dataset" % k
)
if v in self.dims or v in self:
raise ValueError(
f"Cannot rename {k} to {v} because {v} already exists. "
"Try using swap_dims instead."
)

variables, coord_names, sizes, indexes = self._rename_all(
name_dict={}, dims_dict=dims_dict
Expand Down
3 changes: 3 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2444,6 +2444,9 @@ def test_rename_dims(self):
with pytest.raises(ValueError):
original.rename_dims(dims_dict_bad)

with pytest.raises(ValueError):
original.rename_dims({"x": "z"})

def test_rename_vars(self):
original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})
expected = Dataset(
Expand Down

0 comments on commit ef6e6a7

Please sign in to comment.