Select to view content in your preferred language

Intersect a grid with another shp to retrieve information - Python

664
3
02-02-2022 06:34 AM
JabbarKhan
New Contributor

I am using Python and I have two Shapefiles. One is a grid with equal Polygons and the other one is a shapefile representing a water network. I would like to count the pipe length in each cell of this grid. I have tried an overlay method but it returns an empty dataframe whereas both shapefiles have the same CRS.

print("Maillage/canalisation intersection...")
gdf_intersection_maille_cana=gpd.overlay(gdf_maillage,gdf_cana_total,how='intersection')
print(gdf_intersection_maille_cana)
print("Maillage/canalisation intersection done ! ")

The second step would be to count the length in each grid but I don't really how to proceed. Once I have counted, the objective is to create a new column in my gdf_maillage with the pipe length in each cell .

0 Kudos
3 Replies
JohannesLindner
MVP Frequent Contributor

I don't know Geopandas, but if you have access to arcpy, you can do it like this:

grid = "path:/to/grid.shp"
pipes = "path:/to/pipes.shp"
grid_id_field = "GridID"  # unique identifier of your grid features
pipe_length_field = "PipeLength"  # name of the new field

# intersect grid and pipes
intersection = arcpy.analysis.Intersect([grid, pipes], "memory/intersection")

# read intersection into a list
# [ (GridID, PipeShape) ]
intersection_list = [row for row in arcpy.da.SearchCursor(intersection, [grid_id_field, "SHAPE@"])]

# add the new field to the grid
arcpy.management.AddField(grid, pipe_length_field, "DOUBLE")

# loop through the grid and fill the new field
with arcpy.da.UpdateCursor(grid, [grid_id_field, pipe_length_field]) as cursor:
    for grid_id, pipe_length in cursor:
        # get all pipe shapes in this grid cell
        pipe_shapes = [d[1] for d in intersection_list if d[0] == grid_id]
        # get total length of those shapes
        pipe_length = sum([s.length for s in pipe_shapes])
        # update field values
        cursor.updateRow([grid_id, pipe_length])

 


Have a great day!
Johannes
0 Kudos
sophiamartin
New Contributor

Sports have played a significant role in shaping me into a better developer by instilling crucial skills and attributes that are transferable to my professional life. Here are some ways sports have contributed to my development as a software developer:

  1.  

0 Kudos
sophiamartin
New Contributor

SVIs are vital for enabling Layer 3 routing on a switch, facilitating inter-VLAN communication without the need for an external router By following the above steps, you can configure SVIs on your switch, allowing different VLANs to communicate efficiently.

0 Kudos