xarray icon indicating copy to clipboard operation
xarray copied to clipboard

Assign a scalar to a xarray.Dataset

Open m-legrand opened this issue 3 months ago • 2 comments

Is your feature request related to a problem?

If I have a dataset with some coordinates:

dataset = xr.Dataset(coords={"x": [1, 2, 3], "y": [10, 20]})

I would like to be able to create a variable by broadcasting a scalar to the relevant dimensions:

dataset = dataset.assign({"baseline": (("x", "y"), 0)})
# ValueError: Variable 'baseline': Could not convert tuple of form (dims, data[, attrs, encoding]): (('x', 'y'), 0) to Variable.

Instead, I have to build the data myself, which can get unnecessarily verbose and redundant for high dimension data.

arr = np.full((dataset.sizes["x"], dataset.sizes["y"]), np.nan)
dataset = dataset.assign({"baseline": (("x", "y"), arr)})

This is especially surprising given that they're are way more powerful ways of populating a variable, e.g. this could be done with a lambda:

dataset = dataset.assign({"baseline": lambda x: 0*x.x + 0*x.y})  # doesn't work if x or y is non-numeric

Describe the solution you'd like

Ideally I would like to be able to do the following:

dataset = dataset.assign({"baseline": (("x", "y"), 0)})

Describe alternatives you've considered

No response

Additional context

No response

m-legrand avatar Dec 08 '25 16:12 m-legrand

Thanks for opening your first issue here at xarray! Be sure to follow the issue template! If you have an idea for a solution, we would really welcome a Pull Request with proposed changes. See the Contributing Guide for more. It may take us a while to respond here, but we really value your contribution. Contributors like you help make xarray better. Thank you!

welcome[bot] avatar Dec 08 '25 16:12 welcome[bot]

Can you use xr.full_like? https://docs.xarray.dev/en/stable/generated/xarray.full_like.html

dcherian avatar Dec 08 '25 17:12 dcherian