1

I have a netcdf4 file called test.nc

I am calculating monthly median (from the daily values) with the following code:

import xarray as xr
os.chdir(inbasedir)
data = xr.open_dataset('test.nc')
monthly_data = data.resample(freq='m', dim ='time', how = 'median')

My question is how can I write this output to a new netcdf file, without having to re-write all the variables and the metadata already included in the input netcdf file.

steve
  • 511
  • 1
  • 9
  • 33
  • Possible duplicate of [How to create a netCDF file with python netCDF4?](https://stackoverflow.com/questions/34923646/how-to-create-a-netcdf-file-with-python-netcdf4) –  Feb 22 '19 at 15:49
  • @SilverNitrateIon - It's not a duplicate. In my question I simply search how to output the netCDF from an existing one without having to re-write the metadata, variables, already included in the original file. The duplicate you indicate is creating a netcdf file from scratch – steve Feb 22 '19 at 15:51
  • I think there is no shortcut here and you need to copy all vars, dims and attrs: https://stackoverflow.com/questions/13936563/copy-netcdf-file-using-python. One alternative would be to use `nccopy` via `subprocess` – Jarek.D Feb 22 '19 at 16:45

1 Answers1

3

Not sure if it is what you want. But this creates a new netcdf file from the created Dataset:

monthly_data.to_netcdf('newfile.nc')

You might use .drop() on the Dataset to remove data which you don't want in the output.

kmuehlbauer
  • 441
  • 4
  • 7