Set a new, Xarray-compatible index from one or more existing coordinate(s). Existing index(es) on the coord(s) will be replaced. Parameters ---------- coord_names : str or list Name(s) of the coordinate(s) used to build the index. If several n
(
self,
coord_names: str | Sequence[Hashable],
index_cls: type[Index] | None = None,
**options,
)
| 5000 | ) |
| 5001 | |
| 5002 | def set_xindex( |
| 5003 | self, |
| 5004 | coord_names: str | Sequence[Hashable], |
| 5005 | index_cls: type[Index] | None = None, |
| 5006 | **options, |
| 5007 | ) -> Self: |
| 5008 | """Set a new, Xarray-compatible index from one or more existing |
| 5009 | coordinate(s). Existing index(es) on the coord(s) will be replaced. |
| 5010 | |
| 5011 | Parameters |
| 5012 | ---------- |
| 5013 | coord_names : str or list |
| 5014 | Name(s) of the coordinate(s) used to build the index. |
| 5015 | If several names are given, their order matters. |
| 5016 | index_cls : subclass of :class:`~xarray.indexes.Index`, optional |
| 5017 | The type of index to create. By default, try setting |
| 5018 | a ``PandasIndex`` if ``len(coord_names) == 1``, |
| 5019 | otherwise a ``PandasMultiIndex``. |
| 5020 | **options |
| 5021 | Options passed to the index constructor. |
| 5022 | |
| 5023 | Returns |
| 5024 | ------- |
| 5025 | obj : Dataset |
| 5026 | Another dataset, with this dataset's data and with a new index. |
| 5027 | |
| 5028 | """ |
| 5029 | # the Sequence check is required for mypy |
| 5030 | if is_scalar(coord_names) or not isinstance(coord_names, Sequence): |
| 5031 | coord_names = [coord_names] |
| 5032 | |
| 5033 | if index_cls is None: |
| 5034 | if len(coord_names) == 1: |
| 5035 | index_cls = PandasIndex |
| 5036 | else: |
| 5037 | index_cls = PandasMultiIndex |
| 5038 | elif not issubclass(index_cls, Index): |
| 5039 | raise TypeError(f"{index_cls} is not a subclass of xarray.Index") |
| 5040 | |
| 5041 | invalid_coords = set(coord_names) - self._coord_names |
| 5042 | |
| 5043 | if invalid_coords: |
| 5044 | msg = ["invalid coordinate(s)"] |
| 5045 | no_vars = invalid_coords - set(self._variables) |
| 5046 | data_vars = invalid_coords - no_vars |
| 5047 | if no_vars: |
| 5048 | msg.append(f"those variables don't exist: {no_vars}") |
| 5049 | if data_vars: |
| 5050 | msg.append( |
| 5051 | f"those variables are data variables: {data_vars}, use `set_coords` first" |
| 5052 | ) |
| 5053 | raise ValueError("\n".join(msg)) |
| 5054 | |
| 5055 | coord_vars = {name: self._variables[name] for name in coord_names} |
| 5056 | |
| 5057 | index = index_cls.from_variables(coord_vars, options=options) |
| 5058 | |
| 5059 | new_coord_vars = index.create_variables(coord_vars) |