File tree Expand file tree Collapse file tree 4 files changed +22
-2
lines changed Expand file tree Collapse file tree 4 files changed +22
-2
lines changed Original file line number Diff line number Diff line change @@ -4698,7 +4698,9 @@ def set_index(
4698
4698
if len (var_names ) == 1 and (not append or dim not in self ._indexes ):
4699
4699
var_name = var_names [0 ]
4700
4700
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 ,):
4702
4704
raise ValueError (
4703
4705
f"dimension mismatch: try setting an index for dimension { dim !r} with "
4704
4706
f"variable { var_name !r} that has dimensions { var .dims } "
Original file line number Diff line number Diff line change @@ -616,7 +616,14 @@ def from_variables(
616
616
617
617
name , var = next (iter (variables .items ()))
618
618
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 :
620
627
raise ValueError (
621
628
"PandasIndex only accepts a 1-dimensional variable, "
622
629
f"variable { name !r} has { var .ndim } dimensions"
Original file line number Diff line number Diff line change @@ -3397,6 +3397,12 @@ def test_set_index(self) -> None:
3397
3397
with pytest .raises (ValueError , match = r"dimension mismatch.*" ):
3398
3398
ds .set_index (y = "x_var" )
3399
3399
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
+
3400
3406
def test_set_index_deindexed_coords (self ) -> None :
3401
3407
# test de-indexed coordinates are converted to base variable
3402
3408
# https://github.com/pydata/xarray/issues/6969
Original file line number Diff line number Diff line change @@ -145,6 +145,11 @@ def test_from_variables(self) -> None:
145
145
with pytest .raises (ValueError , match = r".*only accepts one variable.*" ):
146
146
PandasIndex .from_variables ({"x" : var , "foo" : var2 }, options = {})
147
147
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
+
148
153
with pytest .raises (
149
154
ValueError , match = r".*only accepts a 1-dimensional variable.*"
150
155
):
You can’t perform that action at this time.
0 commit comments