Skip to content

Adding data variables without specifying nan values explicitly? Only via a list of dimensions? #10605

@doronbehar

Description

@doronbehar

Is your feature request related to a problem?

Very often, I find it much more comfortable when creating complex xarray.Datasets, to create data variables in the following way (also implemented as a workaround just below):

  1. Declare the dimensions, each of which is defined by a 1D array (of varying sizes of course)
  2. Add the data variables based on the sizes of the dimensions the xarray.Dataset is already aware of.

This way, I don't have to manually construct np.full arrays that would fit my data - I only have to specify the dimensions as a list of strings, and the shape is already constructed.

Describe the solution you'd like

I use the following:

def set_dvar_from_dims(self, name, specific_dims, astype=np.float64, **kwargs):
    for kw in ['dims', 'coords']:
        assert kw not in kwargs, (
            f"Don't specify {kw} when using set_data_variable_from_dims, this "
            "doesn't make sense"
        )
    self[name] = xr.DataArray(
        dims=specific_dims,
        coords={dim: self[dim] for dim in specific_dims},
        **kwargs,
    ).astype(astype)
xr.Dataset.set_dvar_from_dims = set_dvar_from_dims

And example usage:

ds = xr.Dataset(
    coords=TEMPERATURES_SOURCES | {
        'mass': self.masses,
        'regime': TEMPERATURES_REGIMES,
        'break_idx': range(TEMPERATURES_REGIMES_AMOUNT + 1), 
        'ns': list("ns"),
        'time|cooling': times,
    },
)
common_dims = ['mass'] + list(TEMPERATURES_SOURCES.keys())
ds.set_dvar_from_dims('coolFreqBreak', common_dims)
ds.set_dvar_from_dims('beta', common_dims + ['break_idx'])
ds.set_dvar_from_dims('coolFreq', common_dims + ['regime', 'ns'])
ds.set_dvar_from_dims("fit_prediction", common_dims + ["time|cooling"])

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