Skip to content

Don't copy the first variable's attrs in to_stacked_array - #11971

Open
AsadullahMaliyawala wants to merge 1 commit into
pydata:mainfrom
AsadullahMaliyawala:fix/to-stacked-array-attrs
Open

AsadullahMaliyawala wants to merge 1 commit into
pydata:mainfrom
AsadullahMaliyawala:fix/to-stacked-array-attrs

Conversation

@AsadullahMaliyawala

Copy link
Copy Markdown

Description

Dataset.to_stacked_array concatenates the per-variable arrays with concat's default combine_attrs="override", so the attrs of whichever data variable comes first end up on the stacked array. to_unstacked_dataset then copies them to every variable, so the metadata of one variable is silently attached to all the others, and the result depends on the variable order:

import numpy as np, xarray as xr

ds = xr.Dataset(
    {"a": (("x", "y"), np.ones((2, 2)), {"units": "K"}), "b": ("x", [1.0, 2.0])},
    coords={"x": [0, 1], "y": [1, 2]},
)
stacked = ds.to_stacked_array("z", sample_dims=["x"])
stacked.attrs                                     # {'units': 'K'}  (b has no units)
stacked.to_unstacked_dataset("z")["b"].attrs      # {'units': 'K'}
ds[["b", "a"]].to_stacked_array("z", ["x"]).attrs  # {}

This drops each variable's own attrs before stacking (drop_attrs(deep=False)), so coordinate attrs are kept. Per-variable attrs can't survive the round trip anyway, since the stacked array has only one attrs dict.

Checklist

  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst

The new test fails on main and passes with the change; test_dataset.py, test_dataarray.py, the stacking tests in test_units.py, the to_stacked_array doctest and ruff pass locally (Windows, Python 3.12).

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: Claude Code (Claude Opus 5.5), used to find the issue by reviewing the stacking code, write the fix and the test.

Dataset.to_stacked_array concatenated the per-variable arrays with
concat's default combine_attrs='override', so the attrs of the first data
variable (e.g. units) became the attrs of the stacked array, and
to_unstacked_dataset then put them on every variable. Drop the variables'
own attrs before stacking; coordinate attrs are kept.
@welcome

welcome Bot commented Dec 2, 2026

Copy link
Copy Markdown

Thank you for opening this pull request! It may take us a few days to respond here, so thank you for being patient.
If you have questions, some answers may be found in our contributing guidelines.

This branch has not been deployed

No deployments
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.

1 participant