Skip to content

Instantly share code, notes, and snippets.

@caffeine-potent
Created April 1, 2019 18:54
Show Gist options
  • Save caffeine-potent/dc2baf50afa7ca46a0c0273992a855af to your computer and use it in GitHub Desktop.
Save caffeine-potent/dc2baf50afa7ca46a0c0273992a855af to your computer and use it in GitHub Desktop.
Exporting an xarray with datacube attributes
import datacube
import xarray as xr
def export_xarray_to_netcdf(ds:xr.Dataset, path:str):
"""
Exports an xarray.Dataset as a single NetCDF file.
Parameters
----------
ds: xarray.Dataset
The Dataset to export.
path: str
The path to store the exported NetCDF file at.
Must include the filename and ".nc" extension.
"""
# Convert any boolean data variables to integer type to be able to export to NetCDF.
for data_var_name in ds.data_vars:
dtype = ds[data_var_name].dtype
if dtype == np.bool:
ds[data_var_name] = ds[data_var_name].astype(np.int8)
datacube.storage.storage.write_dataset_to_netcdf(ds, path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment