Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Bug fixes
- add a ``keep_attrs`` parameter to :py:meth:`Dataset.pad`, :py:meth:`DataArray.pad`,
and :py:meth:`Variable.pad` (:pull:`7267`).
By `Justus Magin <https://github.com/keewis>`_.
- Preserve original dtype on accessing MultiIndex levels (:issue:`7250`,
:pull:`7393`). By `Ian Carroll <https://github.com/itcarroll>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
6 changes: 5 additions & 1 deletion xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1531,8 +1531,12 @@ def __init__(
self.level = level

def __array__(self, dtype: DTypeLike = None) -> np.ndarray:
if dtype is None:
dtype = self.dtype
if self.level is not None:
return self.array.get_level_values(self.level).values
return np.asarray(
self.array.get_level_values(self.level).values, dtype=dtype
)
else:
return super().__array__(dtype)

Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,3 +697,10 @@ def test_safe_cast_to_index_datetime_datetime():
actual = safe_cast_to_index(np.array(dates))
assert_array_equal(expected, actual)
assert isinstance(actual, pd.Index)


@pytest.mark.parametrize("dtype", ["int32", "float32"])
def test_restore_dtype_on_multiindexes(dtype: str) -> None:
foo = xr.Dataset(coords={"bar": ("bar", np.array([0, 1], dtype=dtype))})
foo = foo.stack(baz=("bar",))
assert str(foo["bar"].values.dtype) == dtype