Python NetCDF – How to Save Clipped NetCDF Data as New NetCDF File in Python

clipnetcdfrasterrioxarrayxarray

I have used xarray to clip my NetCDF file‌ (it can be downloaded here) by a shapefile (it can be downloaded from here). Here is the code:

import xarray
import rioxarray
import geopandas
from shapely.geometry import mapping

xds = xarray.open_dataset(
    "3B-DAY.MS.MRG.3IMERG.20170216-S000000-E235959.V06.nc4",)

xds = xds[['precipitationCal', 'precipitationCal_cnt']].transpose('time', 'lat', 'lon')

xds.rio.set_spatial_dims(x_dim="lon", y_dim="lat", inplace=True)
xds.rio.write_crs("EPSG:4326", inplace=True)
geodf = geopandas.read_file("NAME_LONG_201.shp")

clipped = xds.rio.clip(geodf.geometry.apply(mapping), geodf.crs)

Now, I have a clipped object which is of type: xarray.Dataset. How can I save this dataset into a new NetCDF file?

Best Answer

xarray.Dataset has a to_netcdf method...so it should be clipped.to_netcdf(path_on_disk)

http://xarray.pydata.org/en/stable/generated/xarray.Dataset.to_netcdf.html

Related Question