6

Since geopandas can't perform overlay/intersection with lines, I found a workaround:

import geopandas as gpd
import fiona
from shapely.geometry import shape, MultiPolygon, LineString, MultiLineString


lines = gpd.read_file('lines.shp')
polyons= gpd.read_file('polygons.shp')
pol_f = fiona.open('polygons.shp')

pol_shp = MultiPolygon([shape(x["geometry"]) for x in pol_f])

lines2 = lines.geometry.apply(lambda x: x.intersection(pol_shp))
lines2.to_file('lines_int.shp')

But it does not let me because there are the empty geometries are GeometryCollections.

I tried this to filter, but it won't work.

lines3 = lines2[lines2.geometry != np.nan]
lines3 = lines2[lines2.geometry == LineString]
lines3 = lines2[lines2.geometry == LineString()]
lines3 = lines2[lines2.geometry == MultiLineString()]
lines3 = lines2[lines2.geometry == MultiLineString]
lines3 = lines2[lines2.geometry != GeometryCollection]

Any ideas?

5

The GeoDataFrame and GeoSeries have an is_empty attribute, similar to shapely geometry objects. You can use this to filter out the empty ones:

In [7]: lines = geopandas.GeoSeries([
   ...:     LineString([(0, 0), (1, 1)]), LineString([]), LineString([(1, 1), (2, 2)])])

In [8]: lines                             
Out[8]: 
0       LINESTRING (0 0, 1 1)
1    GEOMETRYCOLLECTION EMPTY
2       LINESTRING (1 1, 2 2)
dtype: object

In [9]: lines.is_empty                                      
Out[9]: 
0    False
1     True
2    False
dtype: bool

In [10]: lines[~lines.is_empty]                                            
Out[10]: 
0    LINESTRING (0 0, 1 1)
2    LINESTRING (1 1, 2 2)
dtype: object

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.