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.

3
  • Possible duplicate of How to create a netCDF file with python netCDF4? Commented Feb 22, 2019 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 Commented Feb 22, 2019 at 15:51
  • I think there is no shortcut here and you need to copy all vars, dims and attrs: stackoverflow.com/questions/13936563/…. One alternative would be to use nccopy via subprocess Commented Feb 22, 2019 at 16:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.