Wrap a pandas.Index as an xarray compatible index.
| 649 | |
| 650 | |
| 651 | class PandasIndex(Index): |
| 652 | """Wrap a pandas.Index as an xarray compatible index.""" |
| 653 | |
| 654 | index: pd.Index |
| 655 | dim: Hashable |
| 656 | coord_dtype: Any |
| 657 | |
| 658 | __slots__ = ("coord_dtype", "dim", "index") |
| 659 | |
| 660 | def __init__( |
| 661 | self, |
| 662 | array: Any, |
| 663 | dim: Hashable, |
| 664 | coord_dtype: Any = None, |
| 665 | *, |
| 666 | fastpath: bool = False, |
| 667 | ): |
| 668 | if fastpath: |
| 669 | index = array |
| 670 | else: |
| 671 | index = safe_cast_to_index(array) |
| 672 | |
| 673 | if index.name is None: |
| 674 | # make a shallow copy: cheap and because the index name may be updated |
| 675 | # here or in other constructors (cannot use pd.Index.rename as this |
| 676 | # constructor is also called from PandasMultiIndex) |
| 677 | index = index.copy() |
| 678 | index.name = dim |
| 679 | |
| 680 | self.index = index |
| 681 | self.dim = dim |
| 682 | if coord_dtype is None: |
| 683 | if is_allowed_extension_array_dtype(index.dtype): |
| 684 | cast(pd.api.extensions.ExtensionDtype, index.dtype) |
| 685 | coord_dtype = index.dtype |
| 686 | else: |
| 687 | coord_dtype = get_valid_numpy_dtype(index) |
| 688 | self.coord_dtype = coord_dtype |
| 689 | |
| 690 | def _replace(self, index, dim=None, coord_dtype=None): |
| 691 | if dim is None: |
| 692 | dim = self.dim |
| 693 | if coord_dtype is None: |
| 694 | coord_dtype = self.coord_dtype |
| 695 | return type(self)(index, dim, coord_dtype, fastpath=True) |
| 696 | |
| 697 | @classmethod |
| 698 | def from_variables( |
| 699 | cls, |
| 700 | variables: Mapping[Any, Variable], |
| 701 | *, |
| 702 | options: Mapping[str, Any], |
| 703 | ) -> PandasIndex: |
| 704 | if len(variables) != 1: |
| 705 | raise ValueError( |
| 706 | f"PandasIndex only accepts one variable, found {len(variables)} variables" |
| 707 | ) |
| 708 |
no outgoing calls
searching dependent graphs…