Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

raise an error when renaming dimensions to existing names #3645

Merged
merged 7 commits into from
Jan 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,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