Skip to content

Commit c85f372

Browse files
authored
Preserve original dtype when accessing MultiIndex levels (#7393)
* return multiindex levels as original dtype (#7250) * typing in test, contributor attribution * rst is not markdown
1 parent 41fef6f commit c85f372

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Bug fixes
4545
- add a ``keep_attrs`` parameter to :py:meth:`Dataset.pad`, :py:meth:`DataArray.pad`,
4646
and :py:meth:`Variable.pad` (:pull:`7267`).
4747
By `Justus Magin <https://github.com/keewis>`_.
48+
- Preserve original dtype on accessing MultiIndex levels (:issue:`7250`,
49+
:pull:`7393`). By `Ian Carroll <https://github.com/itcarroll>`_.
4850

4951
Documentation
5052
~~~~~~~~~~~~~

xarray/core/indexing.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1531,8 +1531,12 @@ def __init__(
15311531
self.level = level
15321532

15331533
def __array__(self, dtype: DTypeLike = None) -> np.ndarray:
1534+
if dtype is None:
1535+
dtype = self.dtype
15341536
if self.level is not None:
1535-
return self.array.get_level_values(self.level).values
1537+
return np.asarray(
1538+
self.array.get_level_values(self.level).values, dtype=dtype
1539+
)
15361540
else:
15371541
return super().__array__(dtype)
15381542

xarray/tests/test_indexes.py

+7
Original file line numberDiff line numberDiff line change
@@ -697,3 +697,10 @@ def test_safe_cast_to_index_datetime_datetime():
697697
actual = safe_cast_to_index(np.array(dates))
698698
assert_array_equal(expected, actual)
699699
assert isinstance(actual, pd.Index)
700+
701+
702+
@pytest.mark.parametrize("dtype", ["int32", "float32"])
703+
def test_restore_dtype_on_multiindexes(dtype: str) -> None:
704+
foo = xr.Dataset(coords={"bar": ("bar", np.array([0, 1], dtype=dtype))})
705+
foo = foo.stack(baz=("bar",))
706+
assert str(foo["bar"].values.dtype) == dtype

0 commit comments

Comments
 (0)