Is there some way to add a global attribute to a netCDF
file using xarray
? When I do something like hndl_nc['global_attribute'] = 25
, it just adds a new variable.
Asked
Active
Viewed 9,577 times
7

msi_gerva
- 2,021
- 3
- 22
- 28

user308827
- 21,227
- 87
- 254
- 417
2 Answers
12
In Xarray, directly indexing a Dataset
like hndl_nc['variable_name']
pulls out a DataArray
object. To get or set attributes, index .attrs
like hndl_nc.attrs['global_attribute']
or hndl_nc.attrs['global_attribute'] = 25
.
You can access both variables and attributes using Python's attribute syntax like hndl_nc.variable_or_attribute_name
, but this is a convenience feature that only works when the variable or attribute name does not conflict with a preexisting method or property, and cannot be used for setting.

shoyer
- 9,165
- 1
- 37
- 55
7
I would add here that both Datasets and DataArrays can have attributes, both called with .attrs
e.g.
ds.attrs['global attr'] = 25
ds.variable_2.attrs['variable attr'] = 10
ds.variable_2.attrs['variable attr'] = 10

dreab
- 705
- 3
- 12
- 22