I have used xarray on some satellite data that I'd like to mask it using a shapefile. I have previously been doing this using a combination of PIL, numpy and gdal, but it would be cleaner to do this directly on the xarray dataset with Rasterio and GeoPandas.
I have the following xarray Dataset:
I've opened my shapefile in GeoPandas using:
sf = geopandas.read_file('GRI_jergetal.shp')
I then want to mask my xarray dataset using the shapefile in GeoPandas, and it seems like rasterio.mask.mask
has this capability. However, the code that I have used gives the following error (adding in a nodata and a transform attribute to my xarray as it did not contain those parameters originally).
sf = sf.to_crs('EPSG:32643')
ndvi.attrs['nodata'] = np.nan
ndvi.attrs['transform'] = good_ds.affine
rasterio.mask.mask(ndvi.isel(time=0), sf.loc[0, 'geometry'])
[Output]:
`TypeError: 'Polygon' object is not iterable`.
I've tried a method posted in a previous post Python mask NetCDF data using shapefile (xarray & GeoPandas) & Mask Rasterio raster with GeoPandas shapefile, but the method doesn't seem right for my present case. Have I made a mistake in invoking the rasterio.mask.mask()
function or should I try a different method for getting this to work?
{}
code formatting button.