Skip to content
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

Don't return IndexVariable with .dt accessor #9415

Merged
merged 4 commits into from
Sep 3, 2024
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
16 changes: 13 additions & 3 deletions xarray/core/accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
is_np_timedelta_like,
)
from xarray.core.types import T_DataArray
from xarray.core.variable import IndexVariable
from xarray.core.variable import IndexVariable, Variable
from xarray.namedarray.utils import is_duck_dask_array

if TYPE_CHECKING:
Expand Down Expand Up @@ -244,12 +244,22 @@ def _date_field(self, name: str, dtype: DTypeLike) -> T_DataArray:
if dtype is None:
dtype = self._obj.dtype
result = _get_date_field(_index_or_data(self._obj), name, dtype)
newvar = self._obj.variable.copy(data=result, deep=False)
newvar = Variable(
dims=self._obj.dims,
attrs=self._obj.attrs,
encoding=self._obj.encoding,
data=result,
)
return self._obj._replace(newvar, name=name)

def _tslib_round_accessor(self, name: str, freq: str) -> T_DataArray:
result = _round_field(_index_or_data(self._obj), name, freq)
newvar = self._obj.variable.copy(data=result, deep=False)
newvar = Variable(
dims=self._obj.dims,
attrs=self._obj.attrs,
encoding=self._obj.encoding,
data=result,
)
return self._obj._replace(newvar, name=name)

def floor(self, freq: str) -> T_DataArray:
Expand Down
6 changes: 3 additions & 3 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -1490,7 +1490,7 @@ def _unstack_once(
dim: Hashable,
fill_value=dtypes.NA,
sparse: bool = False,
) -> Self:
) -> Variable:
"""
Unstacks this variable given an index to unstack and the name of the
dimension to which the index refers.
Expand Down Expand Up @@ -1550,10 +1550,10 @@ def _unstack_once(
# case the destinations will be NaN / zero.
data[(..., *indexer)] = reordered

return self._replace(dims=new_dims, data=data)
return self.to_base_variable()._replace(dims=new_dims, data=data)

@partial(deprecate_dims, old_name="dimensions")
def unstack(self, dim=None, **dim_kwargs):
def unstack(self, dim=None, **dim_kwargs) -> Variable:
"""
Unstack an existing dimension into multiple new dimensions.

Expand Down
4 changes: 3 additions & 1 deletion xarray/testing/assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ def assert_identical(a, b, from_root=True):
if isinstance(a, Variable):
assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
elif isinstance(a, DataArray):
assert a.name == b.name
assert (
a.name == b.name
), f"DataArray names are different. L: {a.name}, R: {b.name}"
assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
elif isinstance(a, Dataset | Variable):
assert a.identical(b), formatting.diff_dataset_repr(a, b, "identical")
Expand Down
1 change: 1 addition & 0 deletions xarray/tests/test_accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def test_field_access(self, field) -> None:
actual = getattr(self.data.time.dt, field)
else:
actual = getattr(self.data.time.dt, field)
assert not isinstance(actual.variable, xr.IndexVariable)

assert expected.dtype == actual.dtype
assert_identical(expected, actual)
Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -7202,3 +7202,17 @@ def test_lazy_data_variable_not_loaded():
da = xr.DataArray(v)
# No data needs to be accessed, so no error should be raised
xr.DataArray(da)


def test_unstack_index_var() -> None:
source = xr.DataArray(range(2), dims=["x"], coords=[["a", "b"]])
da = source.x
da = da.assign_coords(y=("x", ["c", "d"]), z=("x", ["e", "f"]))
da = da.set_index(x=["y", "z"])
actual = da.unstack("x")
expected = xr.DataArray(
np.array([["a", np.nan], [np.nan, "b"]], dtype=object),
coords={"y": ["c", "d"], "z": ["e", "f"]},
name="x",
)
assert_identical(actual, expected)
Loading