Create a default index from a dimension variable. Create a PandasMultiIndex if the given variable wraps a pandas.MultiIndex, otherwise create a PandasIndex (note that this will become obsolete once we depreciate implicitly passing a pandas.MultiIndex as a coordinate).
(
dim_variable: Variable,
all_variables: Mapping | Iterable[Hashable] | None = None,
)
| 1628 | |
| 1629 | |
| 1630 | def create_default_index_implicit( |
| 1631 | dim_variable: Variable, |
| 1632 | all_variables: Mapping | Iterable[Hashable] | None = None, |
| 1633 | ) -> tuple[PandasIndex, IndexVars]: |
| 1634 | """Create a default index from a dimension variable. |
| 1635 | |
| 1636 | Create a PandasMultiIndex if the given variable wraps a pandas.MultiIndex, |
| 1637 | otherwise create a PandasIndex (note that this will become obsolete once we |
| 1638 | depreciate implicitly passing a pandas.MultiIndex as a coordinate). |
| 1639 | |
| 1640 | """ |
| 1641 | if all_variables is None: |
| 1642 | all_variables = {} |
| 1643 | if not isinstance(all_variables, Mapping): |
| 1644 | all_variables = dict.fromkeys(all_variables) |
| 1645 | |
| 1646 | name = dim_variable.dims[0] |
| 1647 | array = getattr(dim_variable._data, "array", None) |
| 1648 | index: PandasIndex |
| 1649 | |
| 1650 | if isinstance(array, pd.MultiIndex): |
| 1651 | index = PandasMultiIndex(array, name) |
| 1652 | index_vars = index.create_variables() |
| 1653 | # check for conflict between level names and variable names |
| 1654 | duplicate_names = [k for k in index_vars if k in all_variables and k != name] |
| 1655 | if duplicate_names: |
| 1656 | # dirty workaround for an edge case where both the dimension |
| 1657 | # coordinate and the level coordinates are given for the same |
| 1658 | # multi-index object => do not raise an error |
| 1659 | # TODO: remove this check when removing the multi-index dimension coordinate |
| 1660 | if len(duplicate_names) < len(index.index.names): |
| 1661 | conflict = True |
| 1662 | else: |
| 1663 | duplicate_vars = [all_variables[k] for k in duplicate_names] |
| 1664 | conflict = any( |
| 1665 | v is None or not dim_variable.equals(v) for v in duplicate_vars |
| 1666 | ) |
| 1667 | |
| 1668 | if conflict: |
| 1669 | conflict_str = "\n".join(duplicate_names) |
| 1670 | raise ValueError( |
| 1671 | f"conflicting MultiIndex level / variable name(s):\n{conflict_str}" |
| 1672 | ) |
| 1673 | else: |
| 1674 | dim_var = {name: dim_variable} |
| 1675 | index = PandasIndex.from_variables(dim_var, options={}) |
| 1676 | index_vars = index.create_variables(dim_var) |
| 1677 | |
| 1678 | return index, index_vars |
| 1679 | |
| 1680 | |
| 1681 | # generic type that represents either a pandas or an xarray index |
no test coverage detected
searching dependent graphs…