user308827
user308827

Reputation: 22031

Adding global attribute using xarray

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.

Upvotes: 7

Views: 11427

Answers (2)

dreab
dreab

Reputation: 723

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

Upvotes: 7

shoyer
shoyer

Reputation: 9613

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.

Upvotes: 12

Related Questions