Skip to content

Commit 00f5382

Browse files
committed
allow IndexVariable.name differ from dim name
1 parent 96e3626 commit 00f5382

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

xarray/core/variable.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2590,12 +2590,14 @@ class IndexVariable(Variable):
25902590
unless another name is given.
25912591
"""
25922592

2593-
__slots__ = ()
2593+
__slots__ = ("_name",)
25942594

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

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

2609+
if name is None:
2610+
self._name = self.dims[0]
2611+
else:
2612+
self._name = name
2613+
26072614
def __dask_tokenize__(self) -> object:
26082615
from dask.base import normalize_token
26092616

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

2756-
return self._replace(data=ndata, attrs=attrs, encoding=encoding)
2763+
copied = self._replace(data=ndata, attrs=attrs, encoding=encoding)
2764+
2765+
return copied
2766+
2767+
def _replace(
2768+
self,
2769+
dims=_default,
2770+
data=_default,
2771+
attrs=_default,
2772+
encoding=_default,
2773+
) -> Self:
2774+
replaced = super()._replace(
2775+
dims=dims, data=data, attrs=attrs, encoding=encoding
2776+
)
2777+
replaced._name = self._name
2778+
return replaced
27572779

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

28262848
@property
28272849
def name(self) -> Hashable:
2828-
return self.dims[0]
2850+
return self._name
28292851

28302852
@name.setter
28312853
def name(self, value) -> NoReturn:

0 commit comments

Comments
 (0)