user308827 user308827 - 1 month ago 5
Python Question

Creating output variables and copying attributes in python xarray netcdf4

I can create variables and copy over attributes in netcdf4 like this:

out_var = hndl_out_nc.createVariable(name_var, var.datatype, var.dimensions)
out_var.setncatts({k: var.getncattr(k) for k in var.ncattrs()})

What is the corresponding version for xarray?


If var is an xarray.DataArray, you can put it (along with attributes) into a new xarray.Dataset simply by writing ds[name_] = var. Or you can construct a new DataArray piece by piece with xarray.DataArray(, var.coords, var.dims, var.attrs).