Skip to content

to_base_variable: coerce multiindex data to numpy array #8888

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
BasicIndexer,
OuterIndexer,
PandasIndexingAdapter,
PandasMultiIndexingAdapter,
VectorizedIndexer,
as_indexable,
)
Expand Down Expand Up @@ -530,8 +531,13 @@ def values(self, values):

def to_base_variable(self) -> Variable:
"""Return this variable as a base xarray.Variable"""
if isinstance(self._data, PandasMultiIndexingAdapter):
data = np.asarray(self._data)
else:
data = self._data

return Variable(
self._dims, self._data, self._attrs, encoding=self._encoding, fastpath=True
self._dims, data, self._attrs, encoding=self._encoding, fastpath=True
)

to_variable = utils.alias(to_base_variable, "to_variable")
Expand Down
17 changes: 17 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3514,6 +3514,20 @@ def test_reset_index(self) -> None:
with pytest.raises(ValueError, match=r".*not coordinates with an index"):
ds.reset_index("y")

def test_reset_multi_index_resets_levels(self) -> None:
# ND DataArray that gets stacked along a multiindex
da = DataArray(np.ones((3, 3)), coords={"dim1": [1, 2, 3], "dim2": [4, 5, 6]})
da = da.stack(feature=["dim1", "dim2"])

# Extract just the stacked coordinates for saving in a dataset
ds = Dataset(data_vars={"feature": da.feature})
xr.testing.assertions._assert_internal_invariants(
ds.reset_index(["feature", "dim1", "dim2"]), check_default_indexes=False
) # succeeds
xr.testing.assertions._assert_internal_invariants(
ds.reset_index(["feature"]), check_default_indexes=False
) # fails, but no warning either

def test_reset_index_keep_attrs(self) -> None:
coord_1 = DataArray([1, 2], dims=["coord_1"], attrs={"attrs": True})
ds = Dataset({}, {"coord_1": coord_1})
Expand Down Expand Up @@ -3560,6 +3574,9 @@ def test_reset_index_drop_convert(
assert name not in reset.variables
for name in converted:
assert_identical(reset[name].variable, ds[name].variable.to_base_variable())
# check that variable data is converted back to a numpy array
# (https://github.com/pydata/xarray/issues/8887)
assert isinstance(reset[name].variable._data, np.ndarray)
for old_name, new_name in renamed.items():
assert_identical(ds[old_name].variable, reset[new_name].variable)

Expand Down