Wrap a pandas.Index to preserve dtypes and handle explicit indexing.
| 1896 | |
| 1897 | |
| 1898 | class PandasIndexingAdapter(IndexingAdapter): |
| 1899 | """Wrap a pandas.Index to preserve dtypes and handle explicit indexing.""" |
| 1900 | |
| 1901 | __slots__ = ("_dtype", "array") |
| 1902 | |
| 1903 | array: pd.Index |
| 1904 | _dtype: np.dtype | pd.api.extensions.ExtensionDtype |
| 1905 | |
| 1906 | def __init__( |
| 1907 | self, |
| 1908 | array: pd.Index, |
| 1909 | dtype: DTypeLike | pd.api.extensions.ExtensionDtype | None = None, |
| 1910 | ): |
| 1911 | from xarray.core.indexes import safe_cast_to_index |
| 1912 | |
| 1913 | self.array = safe_cast_to_index(array) |
| 1914 | |
| 1915 | if dtype is None: |
| 1916 | if is_allowed_extension_array(array): |
| 1917 | cast(pd.api.extensions.ExtensionDtype, array.dtype) |
| 1918 | self._dtype = array.dtype |
| 1919 | else: |
| 1920 | self._dtype = get_valid_numpy_dtype(array) |
| 1921 | elif is_allowed_extension_array_dtype(dtype): |
| 1922 | self._dtype = cast(pd.api.extensions.ExtensionDtype, dtype) |
| 1923 | elif HAS_STRING_DTYPE and isinstance(dtype, pd.StringDtype): |
| 1924 | self._dtype = np.dtypes.StringDType(na_object=dtype.na_value) |
| 1925 | else: |
| 1926 | self._dtype = np.dtype(cast(DTypeLike, dtype)) |
| 1927 | |
| 1928 | @property |
| 1929 | def _in_memory(self) -> bool: |
| 1930 | # prevent costly conversion of a memory-saving pd.RangeIndex into a |
| 1931 | # large numpy array. |
| 1932 | return not isinstance(self.array, pd.RangeIndex) |
| 1933 | |
| 1934 | @property |
| 1935 | def dtype(self) -> np.dtype | pd.api.extensions.ExtensionDtype: # type: ignore[override] |
| 1936 | return self._dtype |
| 1937 | |
| 1938 | def _get_numpy_dtype(self, dtype: np.typing.DTypeLike | None = None) -> np.dtype: |
| 1939 | if dtype is None: |
| 1940 | if is_valid_numpy_dtype(self.dtype): |
| 1941 | return cast(np.dtype, self.dtype) |
| 1942 | else: |
| 1943 | return get_valid_numpy_dtype(self.array) |
| 1944 | else: |
| 1945 | return np.dtype(dtype) |
| 1946 | |
| 1947 | def __array__( |
| 1948 | self, |
| 1949 | dtype: np.typing.DTypeLike | None = None, |
| 1950 | /, |
| 1951 | *, |
| 1952 | copy: bool | None = None, |
| 1953 | ) -> np.ndarray: |
| 1954 | dtype = self._get_numpy_dtype(dtype) |
| 1955 | array = self.array |
no outgoing calls
no test coverage detected
searching dependent graphs…