Skip to content

Assign a scalar to a xarray.Dataset #10996

@m-legrand

Description

@m-legrand

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions