Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 203
Vinod Kumar Avatar asked Oct 17 '25 13:10

Vinod Kumar


1 Answers

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."),)
like image 189
Mathi Avatar answered Oct 20 '25 03:10

Mathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!