Reputation: 1622
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
?
Upvotes: 4
Views: 4477
Reputation: 364
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://xarray.pydata.org/en/stable/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."),)
Upvotes: 9