Skip to content

Instantly share code, notes, and snippets.

@mikecharles
Created July 18, 2019 19:05
Show Gist options
  • Save mikecharles/4a758e81a6af88697ef2a00b9f53e3ed to your computer and use it in GitHub Desktop.
Save mikecharles/4a758e81a6af88697ef2a00b9f53e3ed to your computer and use it in GitHub Desktop.
Create a NetCDF file in Python

This is a simple example that creates a NetCDF file for 1 degree global 2m temperature. There is no time coordinate.

For this portion of code:

ds = xr.DataArray(data, ...)

data is a NumPy array, assumed to have a shape of num_lats x num_lons

You can put whatever attributes you want in the attrs dictionary (eg. 'email': '[email protected]', etc.).

You can name the dataset whatever you want (eg. 'tmean' as above).

This portion of code:

encoding={var: dict(zlib=True, complevel=9) for var in ds.data_vars}

sets the compression of all the variables. The compression is NetCDF4 compression, from 1-9.

import xarray as xr
import numpy as np
# Set xarray DataArray metadata for the NetCDF file
ds_dims = ['lat', 'lon']
ds_coords = {'lat': np.arange(-90, 90+1, 1), 'lon': np.arange(0, 359+1, 1)}
# Create a DataArray and write it to a NetCDF file (assuming data has a shape of (num_lats x num_lons))
ds = xr.DataArray(data, coords=ds_coords, dims=ds_dims, attrs={'long_name': '2m Temperature'},
name='tmean').to_dataset()
ds.to_netcdf('out.nc', encoding={var: dict(zlib=True, complevel=9) for var in ds.data_vars})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment