iterate over features to mask a raster file

50 views Asked by At

I have a raster layer and a shapefile with multiple polygons. I want to iterate over the features (polygons) to mask the raster layer and then get some statistic for each masked features. However, I get an error that "IndexingError: Too many indexers". I can save each feature in separate shapefile and use it to mask the raster layer without any error. However, I want do this through a loop, because I have thousands of features in my shapefile.

import pandas as pd
import numpy as np
import geopandas as gpd
import rasterio as rio
import rasterio.mask
from osgeo import gdal
from osgeo import ogr
from shapely.geometry import mapping
import rioxarray as rxr 

shpfile=gpd.read_file('shapefile.shp')
raster=rxr.open_rasterio('raster.tif')

for index, row in shapefile.iterrows():
    shp=row.loc[index, 'geometry']
    raster_clipped = raster.rio.clip(shp.geometry.apply(mapping))
1

There are 1 answers

0
Jabbar On

I solved it by,

for row in shapefile.iterrows():
     shp=pd.DataFrame(row[1]).T
     raster_clipped = raster.rio.clip(shp.geometry.apply(mapping))