2

I have a folder full of shapefiles, I would like to read them into geopandas and then clip them all to one boundary iteratively. I have loaded all of the shapefiles into a list with this correctly thanks to @Kadir Şahbaz:

import glob
import geopandas as gpd
shapefiles = glob.iglob('E:/folder/shapefiles/*.shp')

gdfs = [gpd.read_file(file) for file in shapefiles]

However now I am stuck on iterating through each shapefile (geodataframe in the list gdfs). The code below only applies the clip to the first shapefile(item) in the list:

for shapefiles in gdfs:
    clipped = [gpd.clip(shapefiles, boundary)

I need to iterate the clip through each shapefile(geodataframe) in the list (and later save each as a separate shapefile).

0
4

A list comprehension is very Python.

clipped = [gpd.clip(s, boundary) for s in shapefiles]

But often it's easier and more flexible to loop, especially if there are clip polygons for each shapefile. Let's say clip_bounds contains a list of clip bounds in the same order as the shapefile list:

shapefiles = glob.iglob('E:/folder/shapefiles/*.shp')
for file, clipper in list(zip(shapefiles,clip_bounds)):
    gpd.clip(gpd.read_file(file),clipper).to_file(file.replace('.shp','.clipped.shp')
    
0
1

Following code you can use to get what you want:

for shapefiles in gdfs:
    clipped = gpd.clip(shapefiles, boundary)
    clipped.to_file("your local system path")

Here I assume that your all shapefiles and boundary polygon are having same projections. If not then you can change the projection of your boundary polygon (if it's also in a geodataframe by using boundary.to_crs(shapefiles.crs)) in run time and then use the above code which I have written. Or if your boundary polygon is not in geodataframe (it's simply a polygon) then you can use from "shapely.ops import transform" module to change the projection to the projection of your shapefiles.

1
  • Sorry but the code you have written does not iterate (clip) through each geodataframe (shapefiles) in the list (gdfs), instead it only clips the first geodataframe and stores it as a single geodataframe which does not solve my problem. Also I will need to save each geodataframe in the list into a separate shapefile so clipped.to_file("your local system path") will not work for that either
    – hughbk
    Apr 22 '21 at 4:53

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.