I have 7000 nc4 files and I need to clip netCDF files based on a shapefile, but I have a problem with rasterio. After I run this code, I got the error:

#AttributeError: module 'rasterio' has no attribute 'features'

shapefile = 'polbnda_sau.shp'

sf = geopandas.read_file(shapefile)
shape_mask = rasterio.features.geometry_mask(sf.iloc[0],
                                      out_shape=(len(ndvi.y), len(ndvi.x)),
shape_mask = xarray.DataArray(shape_masj , dims=("y", "x"))

file_list = sorted(glob.glob("C:\\Sample_to_analysis_netcdf\\DATA\\*.nc4"))

for file in file_list:
    nc_file = xarray.open_dataset(file)
    masked_netcdf_file = nc_file.where(shape_mask == True, drop=True)

2 Answers 2


You need to import rasterio.features explicitly as a module:

>>> import rasterio
>>> rasterio.features
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'rasterio' has no attribute 'features'


>>> import rasterio.features
>>> rasterio.features
<module 'rasterio.features' from '/home/user/.local/lib/python3.8/site-packages/rasterio/features.py'>

I had a similar issue, I think you can do that by using the combination of "regionmask" and 'xarray' in python. I followed these steps:

  1. Store the geometry from geopandas to another variable In your case, (polyfile = sf.geometry[0]) where geometry = [0,1,2..] depend upon number of polygons.
  2. Create a region objects, region_object = regionmask.Regions([polyfile])
  3. xarray to open netcdf file (ds = xr.open_dataset(r'abc.nc')) or (ds = xr.open_mfdataset(r'*.nc')).
  4. Creating mask (mask = region_object.mask(ds.isel(time = 0), lat_name = 'lat', lon_name = 'lon')
  5. place the mask over overall netcdf and extract values (masked_nc_shp = ds.variable_name.where(mask ==0).
  6. Save new file in directory ( masked_nc_shp.to_netcdf(r'../masked_nc_shp.nc')

Note: This method may not work for older or future versions of regionmask. Plus you can also create region object through geoDataFrame directly: Please follow: https://regionmask.readthedocs.io/en/stable/notebooks/geopandas.html

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.