Skip to content

Commit e5a38f6

Browse files
authored
better error message set index from scalar coord (#8109)
1 parent 1fedfd8 commit e5a38f6

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

xarray/core/dataset.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4698,7 +4698,9 @@ def set_index(
46984698
if len(var_names) == 1 and (not append or dim not in self._indexes):
46994699
var_name = var_names[0]
47004700
var = self._variables[var_name]
4701-
if var.dims != (dim,):
4701+
# an error with a better message will be raised for scalar variables
4702+
# when creating the PandasIndex
4703+
if var.ndim > 0 and var.dims != (dim,):
47024704
raise ValueError(
47034705
f"dimension mismatch: try setting an index for dimension {dim!r} with "
47044706
f"variable {var_name!r} that has dimensions {var.dims}"

xarray/core/indexes.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,14 @@ def from_variables(
616616

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

619-
if var.ndim != 1:
619+
if var.ndim == 0:
620+
raise ValueError(
621+
f"cannot set a PandasIndex from the scalar variable {name!r}, "
622+
"only 1-dimensional variables are supported. "
623+
f"Note: you might want to use `obj.expand_dims({name!r})` to create a "
624+
f"new dimension and turn {name!r} as an indexed dimension coordinate."
625+
)
626+
elif var.ndim != 1:
620627
raise ValueError(
621628
"PandasIndex only accepts a 1-dimensional variable, "
622629
f"variable {name!r} has {var.ndim} dimensions"

xarray/tests/test_dataset.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3397,6 +3397,12 @@ def test_set_index(self) -> None:
33973397
with pytest.raises(ValueError, match=r"dimension mismatch.*"):
33983398
ds.set_index(y="x_var")
33993399

3400+
ds = Dataset(coords={"x": 1})
3401+
with pytest.raises(
3402+
ValueError, match=r".*cannot set a PandasIndex.*scalar variable.*"
3403+
):
3404+
ds.set_index(x="x")
3405+
34003406
def test_set_index_deindexed_coords(self) -> None:
34013407
# test de-indexed coordinates are converted to base variable
34023408
# https://github.com/pydata/xarray/issues/6969

xarray/tests/test_indexes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ def test_from_variables(self) -> None:
145145
with pytest.raises(ValueError, match=r".*only accepts one variable.*"):
146146
PandasIndex.from_variables({"x": var, "foo": var2}, options={})
147147

148+
with pytest.raises(
149+
ValueError, match=r".*cannot set a PandasIndex.*scalar variable.*"
150+
):
151+
PandasIndex.from_variables({"foo": xr.Variable((), 1)}, options={})
152+
148153
with pytest.raises(
149154
ValueError, match=r".*only accepts a 1-dimensional variable.*"
150155
):

0 commit comments

Comments
 (0)