Skip to content

Preserve original dtype when accessing MultiIndex levels #7393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 24, 2022
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