@@ -106,14 +106,26 @@ def decode_compress_to_multi_index(encoded, idxnames=None):
106
106
names = encoded [idxname ].attrs ["compress" ].split (" " )
107
107
shape = [encoded .sizes [dim ] for dim in names ]
108
108
indices = np .unravel_index (encoded [idxname ].data , shape )
109
- arrays = [encoded [dim ].data [index ] for dim , index in zip (names , indices )]
110
- mindex = pd .MultiIndex .from_arrays (arrays , names = names )
111
-
112
- decoded .coords [idxname ] = mindex
113
- decoded .coords [idxname ].attrs = encoded [idxname ].attrs .copy ()
114
- for coord in mindex .names :
115
- decoded [coord ].attrs = encoded [coord ].attrs .copy ()
116
- decoded [coord ].encoding = encoded [coord ].encoding .copy ()
109
+ try :
110
+ from xarray .indexes import PandasMultiIndex
111
+
112
+ variables = {
113
+ dim : encoded [dim ].isel ({dim : xr .Variable (data = index , dims = idxname )})
114
+ for dim , index in zip (names , indices )
115
+ }
116
+ decoded = decoded .assign_coords (variables ).set_xindex (
117
+ names , PandasMultiIndex
118
+ )
119
+ except ImportError :
120
+ arrays = [encoded [dim ].data [index ] for dim , index in zip (names , indices )]
121
+ mindex = pd .MultiIndex .from_arrays (arrays , names = names )
122
+ decoded .coords [idxname ] = mindex
123
+
124
+ decoded [idxname ].attrs = encoded [idxname ].attrs .copy ()
125
+ for coord in names :
126
+ variable = encoded ._variables [coord ]
127
+ decoded [coord ].attrs = variable .attrs .copy ()
128
+ decoded [coord ].encoding = variable .encoding .copy ()
117
129
del decoded [idxname ].attrs ["compress" ]
118
130
119
131
return decoded
0 commit comments