Skip to content

Commit

Permalink
better error message set index from scalar coord (#8109)
Browse files Browse the repository at this point in the history
  • Loading branch information
benbovy authored Aug 30, 2023
1 parent 1fedfd8 commit e5a38f6
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
4 changes: 3 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4698,7 +4698,9 @@ def set_index(
if len(var_names) == 1 and (not append or dim not in self._indexes):
var_name = var_names[0]
var = self._variables[var_name]
if var.dims != (dim,):
# an error with a better message will be raised for scalar variables
# when creating the PandasIndex
if var.ndim > 0 and var.dims != (dim,):
raise ValueError(
f"dimension mismatch: try setting an index for dimension {dim!r} with "
f"variable {var_name!r} that has dimensions {var.dims}"
Expand Down
9 changes: 8 additions & 1 deletion xarray/core/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,14 @@ def from_variables(

name, var = next(iter(variables.items()))

if var.ndim != 1:
if var.ndim == 0:
raise ValueError(
f"cannot set a PandasIndex from the scalar variable {name!r}, "
"only 1-dimensional variables are supported. "
f"Note: you might want to use `obj.expand_dims({name!r})` to create a "
f"new dimension and turn {name!r} as an indexed dimension coordinate."
)
elif var.ndim != 1:
raise ValueError(
"PandasIndex only accepts a 1-dimensional variable, "
f"variable {name!r} has {var.ndim} dimensions"
Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3397,6 +3397,12 @@ def test_set_index(self) -> None:
with pytest.raises(ValueError, match=r"dimension mismatch.*"):
ds.set_index(y="x_var")

ds = Dataset(coords={"x": 1})
with pytest.raises(
ValueError, match=r".*cannot set a PandasIndex.*scalar variable.*"
):
ds.set_index(x="x")

def test_set_index_deindexed_coords(self) -> None:
# test de-indexed coordinates are converted to base variable
# https://github.com/pydata/xarray/issues/6969
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ def test_from_variables(self) -> None:
with pytest.raises(ValueError, match=r".*only accepts one variable.*"):
PandasIndex.from_variables({"x": var, "foo": var2}, options={})

with pytest.raises(
ValueError, match=r".*cannot set a PandasIndex.*scalar variable.*"
):
PandasIndex.from_variables({"foo": xr.Variable((), 1)}, options={})

with pytest.raises(
ValueError, match=r".*only accepts a 1-dimensional variable.*"
):
Expand Down

0 comments on commit e5a38f6

Please sign in to comment.