Used by stack and unstack to get one pandas (multi-)index among the indexed coordinates along dimension `dim`. If exactly one index is found, return it with its corresponding coordinate variables(s), otherwise return None and an empty dict. If `create_index=True`, c
(
self,
dim,
multi=False,
create_index=False,
)
| 5165 | return self._replace(variables, indexes=indexes) |
| 5166 | |
| 5167 | def _get_stack_index( |
| 5168 | self, |
| 5169 | dim, |
| 5170 | multi=False, |
| 5171 | create_index=False, |
| 5172 | ) -> tuple[Index | None, dict[Hashable, Variable]]: |
| 5173 | """Used by stack and unstack to get one pandas (multi-)index among |
| 5174 | the indexed coordinates along dimension `dim`. |
| 5175 | |
| 5176 | If exactly one index is found, return it with its corresponding |
| 5177 | coordinate variables(s), otherwise return None and an empty dict. |
| 5178 | |
| 5179 | If `create_index=True`, create a new index if none is found or raise |
| 5180 | an error if multiple indexes are found. |
| 5181 | |
| 5182 | """ |
| 5183 | stack_index: Index | None = None |
| 5184 | stack_coords: dict[Hashable, Variable] = {} |
| 5185 | |
| 5186 | for name, index in self._indexes.items(): |
| 5187 | var = self._variables[name] |
| 5188 | if ( |
| 5189 | var.ndim == 1 |
| 5190 | and var.dims[0] == dim |
| 5191 | and ( |
| 5192 | # stack: must be a single coordinate index |
| 5193 | (not multi and not self.xindexes.is_multi(name)) |
| 5194 | # unstack: must be an index that implements .unstack |
| 5195 | or (multi and type(index).unstack is not Index.unstack) |
| 5196 | ) |
| 5197 | ): |
| 5198 | if stack_index is not None and index is not stack_index: |
| 5199 | # more than one index found, stop |
| 5200 | if create_index: |
| 5201 | raise ValueError( |
| 5202 | f"cannot stack dimension {dim!r} with `create_index=True` " |
| 5203 | "and with more than one index found along that dimension" |
| 5204 | ) |
| 5205 | return None, {} |
| 5206 | stack_index = index |
| 5207 | stack_coords[name] = var |
| 5208 | |
| 5209 | if create_index and stack_index is None: |
| 5210 | if dim in self._variables: |
| 5211 | var = self._variables[dim] |
| 5212 | else: |
| 5213 | _, _, var = _get_virtual_variable(self._variables, dim, self.sizes) |
| 5214 | # dummy index (only `stack_coords` will be used to construct the multi-index) |
| 5215 | stack_index = PandasIndex([0], dim) |
| 5216 | stack_coords = {dim: var} |
| 5217 | |
| 5218 | return stack_index, stack_coords |
| 5219 | |
| 5220 | def _stack_once( |
| 5221 | self, |
no test coverage detected