[GIS] Difference between lines and polygons using geopandas

differencesgeopandasoverlaypython

I wanted to geopandas.overlay() on lines and polygons : get the geometries from the lines that are not in the polygons.

I tried using geopandas for this :

result = gpd.overlay(my_lines, my_polygons, how='difference')

but I get this error :

TypeError: overlay only takes GeoDataFrames with (multi)polygon
geometries

since the overlay method only supports polygons, I did the difference using pyqgis. However I want to know if there is a way to bypass this typeError using geopandas and shapely ?

Best Answer

Meanwhile here is the solution I wrote using pyqgis, it works for me :

my_lines = QgsVectorLayer('/path/to/my_lines.shp', 'my_lines', 'ogr')
my_polygons = QgsVectorLayer('/path/to/my_polygons.shp', 'my_polygons', 'ogr')

diff = processing.runalg("qgis:difference", my_lines, my_polygons, False, None)
result = processing.getObject(diff['OUTPUT'])
_writer = QgsVectorFileWriter.writeAsVectorFormat(result,"/path/to/result.shp","utf-8",None,"ESRI Shapefile")

my_lines_diff_my_polygons = gpd.read_file('/path/to/result.shp')

for this to work, one has to import processing:

import processing