1

I have two shapefiles: Boundary.shp and Lines.shp. I want to clip the lines inside one boundary polygon.

    import geopandas as gpd
        
    fn_boundary = "D\Boundary.shp"
    fn_aerial = "D\Lines.shp"
    df_boundary = gpd.read_file(fn_boundary)['geometry']
    df_boundary_list = df_boundary.tolist()
    x = df_boundary_list[0]
    df_aerial = gpd.read_file(fn_aerial)
    poly_gdf = gpd.GeoDataFrame([1], geometry=[x], crs=df_aerial.crs)
    df_aerial_clipped = gpd.clip(df_aerial,poly_gdf)

**>>> print(df_aerial_clipped)

Empty GeoDataFrame
Columns: [Length, Placement, geometry]
Index: []**

Why does it return an empty data frame? This code works fine for another set of shape files. But for these two shape files, it is returning an empty data frame. What is the issue with the shape files? Or is there any mistake in the code??

I have uploaded both the shape files at this link.

1 Answer 1

0

The problem is that your shapefiles are in different coordinate systems and you are setting (not reprojecting) the clipped layer to the incorrect system. Change your crs=df_aerial.crs to crs=df_boundary.crs. If you want the output to be in your aerial crs then you could add df.to_crs().

import geopandas as gpd
    
fn_boundary = "D:/Downloads/shapes/Boundary.shp"
fn_aerial = "D:/Downloads/shapes/Lines2.shp"
df_aerial = gpd.read_file(fn_aerial)
df_boundary = gpd.read_file(fn_boundary)['geometry']

df_boundary = df_boundary.to_crs(df_aerial.crs)

df_boundary_list = df_boundary.tolist()
x = df_boundary_list[0]
poly_gdf = gpd.GeoDataFrame([1], geometry=[x], crs=df_aerial.crs)
df_aerial_clipped = gpd.clip(df_aerial,poly_gdf)
print(df_aerial_clipped)
df_aerial_clipped.to_file('D:/Downloads/shapes/out.shp')
2
  • Thanks for your answer. But it still returns an empty DataFrame at my end! :( Is it returning the clipped features at your end? Jul 27, 2022 at 3:38
  • 1
    I changed "df_boundary.to_crs(df_aerial.crs)" to "df_boundary = df_boundary.to_crs(df_aerial.crs)" It works now :) Jul 27, 2022 at 4:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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