pythonnetcdfpython-xarray

xarray create variables attributes


I want to create a dataset with xarray and want to add attributes to variables while creating the dataset. The xarray documentation provides a way of adding global attribute. For example, as below:

ds = xr.Dataset(
data_vars=dict(
    'temperature'=(["x", "y", "time"], temperature),
    'precipitation'=(["x", "y", "time"], precipitation),
),
coords=dict(
    lon=(["x", "y"], lon),
    lat=(["x", "y"], lat),
    time=time,
    reference_time=reference_time,
),
attrs=dict(description="Weather related data."),)

One way to add variable attribute would be some like this:

ds['temperature'].attrs = {"units": K, '_FillValue': -999}

But, in my opinion it is more like updating the attribute. Is there a way to directly assign attributes while creating the dataset directly using xr.Dataset ?


Solution

  • Yes, you can directly define variable attributes when defining the data_vars. You just need to provide the attributes in a dictionary Form. See also: https://docs.xarray.dev/en/v2022.10.0/internals/variable-objects.html

    In your example above that would be:

    ds = xr.Dataset(
    data_vars=dict(
        temperature=(["x", "y", "time"], temperature,{'units':'K'}),
        precipitation=(["x", "y", "time"], precipitation,{'units':'mm/day'}),
    ),
    coords=dict(
        lon=(["x", "y"], lon),
        lat=(["x", "y"], lat),
        time=time,
        reference_time=reference_time,
    ),
    attrs=dict(description="Weather related data."),)