Skip to content

Return a copy from get_index - #11563

Open
chiruu12 wants to merge 1 commit into
pydata:mainfrom
chiruu12:fix/2949-index-view
Open

Return a copy from get_index#11563
chiruu12 wants to merge 1 commit into
pydata:mainfrom
chiruu12:fix/2949-index-view

Conversation

@chiruu12

@chiruu12 chiruu12 commented Sep 5, 2026

Copy link
Copy Markdown

Fixes #2949.

get_index returned the stored pandas index. pandas allows .name to be set in place, so a caller could rename the coordinate of the array or dataset they got the index from:

array = xr.DataArray(np.zeros(2), coords={"x": ["a", "b"]}, dims=["x"])
array.get_index("x").name = "renamed"
array.get_index("x").name   # 'renamed' before this change, 'x' after

Dataset was affected the same way, since get_index lives on DataWithCoords.

The change is a copy(deep=False) on the way out. #3126 proposed the same fix in 2019 and stalled on a question about whether it would cost anything, which nobody answered. It does not. A shallow copy of a pandas index is constant time, since the object is immutable and the copy shares the same array:

      1,000 elements   1.16 us
  1,000,000 elements   1.15 us
 10,000,000 elements   1.19 us

pandas 3.0.5, mean of 10000 calls. The comment at xarray/core/variable.py:3005 already states this.

Scope note. Indexes.__getitem__ still returns the stored object, so ds.indexes["x"] is unchanged. xarray/tests/test_indexes.py:630 asserts that identity, so copying there is an API decision rather than a bug fix, and I left it alone. to_index() and to_dataframe() were already safe because they route through set_names().

Tests: one in test_dataarray.py and one in test_dataset.py. Both fail on main and pass here.

Copilot AI lite review requested due to automatic review settings September 5, 2026 09:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

xr.DataArray.to_series returns a (mutable) view

2 participants