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(

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?

1 Answer 1


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


  • Dear @bcollins, it gives me this error: AttributeError: module 'dask' has no attribute 'base'. I think I have to pip install dask.
    – Muser
    Jul 16, 2020 at 7:53
  • I uninstalled and installed dask again. Still got the above error.
    – Muser
    Jul 16, 2020 at 7:56
  • @Muser hey, which version of dask? ``` import dask print(dask.__version__) ```
    – bcollins
    Jul 16, 2020 at 7:59
  • 2
    it worked. Thank you. The problem resolved after I reopened my Python IDE. Before closing the IDE, I installed dask like this: pip install dask[complete] and after installation completed, restarted IDE and it worked
    – Muser
    Jul 16, 2020 at 8:05
  • 1
    @Muser Xarray-Spatial contains a bunch of spatial utility functions (crop, trim, slope, zonal stats etc.) on top of xarray.DataArrays...without a GDAL dependency...FYI, I lead the project so feel free to post questions / issues / code review to the github issues area: github.com/makepath/xarray-spatial/issues
    – bcollins
    Jul 16, 2020 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.