CodeBreak 16/03/2022

Copying global attributes from NetCDF

There was a question where data was converted using a python notebook and xarray, but the global attributes of the input file should be copied over to the output file.

The new file was saved using the line 

pr.to_dataset(name='pr').to_netcdf(<filename>)

We recommended to do it in two steps, and add the copying of the attributes in between:  

ds = pr.to_dataset(name='pr') 
ds.attrs = f.attrs 
ds.to_netcddf(<filename>)

Calculating differential in xarray

The question revolved around calculating the differential of the density (⍴) with respect to the depth (z). Attempting this calculation using np.gradient led to broadcasting errors. It is much easier to use an xarray aware function like xarray.differentiate, which knows how to broadcast because of the named coordinates and uses the spacing in the zcoordinate to properly calculate the differential δ⍴/δz.

Regression analysis on spatial data

The question was about the suitability of using xarray.Dataset.polyfitto do regression analysis on spatial data. This might not be the correct tool, as it has limited options for the fitting function. If more than a simple fit is required, it might be better to use something like sklearn-xarrayor wrap scipy.stats.lingressin a function and apply this to all points.