5
5
import numpy as np
6
6
import pandas as pd
7
7
import xarray as xr
8
+ from packaging .version import Version
8
9
9
10
from .aggregations import Aggregation , _atleast_1d
10
11
from .core import (
@@ -345,12 +346,16 @@ def wrapper(array, *by, func, skipna, **kwargs):
345
346
expect = expect .to_numpy ()
346
347
if isinstance (actual , xr .Dataset ) and name in actual :
347
348
actual = actual .drop_vars (name )
348
- actual [name ] = expect
349
-
350
- # if grouping by multi-indexed variable, then restore it
351
- for name , index in ds .indexes .items ():
352
- if name in actual .indexes and isinstance (index , pd .MultiIndex ):
353
- actual [name ] = index
349
+ # When grouping by MultiIndex, expect is an pd.Index wrapping
350
+ # an object array of tuples
351
+ if name in ds .indexes and isinstance (ds .indexes [name ], pd .MultiIndex ):
352
+ levelnames = ds .indexes [name ].names
353
+ expect = pd .MultiIndex .from_tuples (expect .values , names = levelnames )
354
+ actual [name ] = expect
355
+ if Version (xr .__version__ ) > Version ("2022.03.0" ):
356
+ actual = actual .set_coords (levelnames )
357
+ else :
358
+ actual [name ] = expect
354
359
355
360
if unindexed_dims :
356
361
actual = actual .drop_vars (unindexed_dims )
@@ -361,7 +366,8 @@ def wrapper(array, *by, func, skipna, **kwargs):
361
366
template = obj
362
367
else :
363
368
template = obj [var ]
364
- actual [var ] = _restore_dim_order (actual [var ], template , by [0 ])
369
+ if actual [var ].ndim > 1 :
370
+ actual [var ] = _restore_dim_order (actual [var ], template , by [0 ])
365
371
366
372
if missing_dim :
367
373
for k , v in missing_dim .items ():
@@ -370,9 +376,9 @@ def wrapper(array, *by, func, skipna, **kwargs):
370
376
}
371
377
# The expand_dims is for backward compat with xarray's questionable behaviour
372
378
if missing_group_dims :
373
- actual [k ] = v .expand_dims (missing_group_dims )
379
+ actual [k ] = v .expand_dims (missing_group_dims ). variable
374
380
else :
375
- actual [k ] = v
381
+ actual [k ] = v . variable
376
382
377
383
if isinstance (obj , xr .DataArray ):
378
384
return obj ._from_temp_dataset (actual )
0 commit comments