Skip to content

Commit

Permalink
allow IndexVariable.name differ from dim name
Browse files Browse the repository at this point in the history
  • Loading branch information
benbovy committed Apr 4, 2024
1 parent 96e3626 commit 00f5382
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2590,12 +2590,14 @@ class IndexVariable(Variable):
unless another name is given.
"""

__slots__ = ()
__slots__ = ("_name",)

# TODO: PandasIndexingAdapter doesn't match the array api:
_data: PandasIndexingAdapter # type: ignore[assignment]

def __init__(self, dims, data, attrs=None, encoding=None, fastpath=False):
def __init__(
self, dims, data, attrs=None, encoding=None, fastpath=False, name=None
):
super().__init__(dims, data, attrs, encoding, fastpath)
if self.ndim != 1:
raise ValueError(f"{type(self).__name__} objects must be 1-dimensional")
Expand All @@ -2604,6 +2606,11 @@ def __init__(self, dims, data, attrs=None, encoding=None, fastpath=False):
if not isinstance(self._data, PandasIndexingAdapter):
self._data = PandasIndexingAdapter(self._data)

if name is None:
self._name = self.dims[0]
else:
self._name = name

def __dask_tokenize__(self) -> object:
from dask.base import normalize_token

Expand Down Expand Up @@ -2753,7 +2760,22 @@ def copy(self, deep: bool = True, data: T_DuckArray | ArrayLike | None = None):
attrs = copy.deepcopy(self._attrs) if deep else copy.copy(self._attrs)
encoding = copy.deepcopy(self._encoding) if deep else copy.copy(self._encoding)

return self._replace(data=ndata, attrs=attrs, encoding=encoding)
copied = self._replace(data=ndata, attrs=attrs, encoding=encoding)

return copied

def _replace(
self,
dims=_default,
data=_default,
attrs=_default,
encoding=_default,
) -> Self:
replaced = super()._replace(
dims=dims, data=data, attrs=attrs, encoding=encoding
)
replaced._name = self._name
return replaced

def equals(self, other, equiv=None):
# if equiv is specified, super up
Expand Down Expand Up @@ -2825,7 +2847,7 @@ def get_level_variable(self, level):

@property
def name(self) -> Hashable:
return self.dims[0]
return self._name

@name.setter
def name(self, value) -> NoReturn:
Expand Down

0 comments on commit 00f5382

Please sign in to comment.