5

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 ?

1
  • 1
    You can use a buffer around my_lines (to have polygons). Then run result = gpd.overlay(my_buffered_lines, my_polygons, how='difference') You will have the difference between the buffered lines and the polygons. After that, you can use an intersection between my_lines and my_buffered_lines, this will give you the Linestrings you need
    – Hamri Said
    Commented Jul 11, 2017 at 13:22

1 Answer 1

3

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
3
  • Hello, I am trying to use your solution, but the resultant shape file seems to have an empty geometry field, so there's no useful data in it. Have you run into this issue?
    – Kiran K.
    Commented Jan 12, 2018 at 13:35
  • @KiranK. make sure both your vector layers have the same projection, then if the problem persists close qgis if opened and delete the result file then launch the processing again Commented Jan 12, 2018 at 13:59
  • 1
    Thank you, I posted too quickly, this time, I made sure both were in the same CRS and it does work. Best Regards, and thanks again!
    – Kiran K.
    Commented Jan 12, 2018 at 14:08

Your Answer

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

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