14

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?

2 Answers 2

17

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
1

I'm commenting this post 3 years after @joris answer. In GeoPandas v0.6.0, the missing data handling was refactored and made more consistent across the library. From this version on, GeoSeries.isna() no longer treating empty as missing:

#For GeoPandas<v0.6.0
print(s)
0    POLYGON ((0 0, 1 1, 0 1, 0 0))
1                              None
2          GEOMETRYCOLLECTION EMPTY
dtype: object

print(s.isna())
0    False
1     True
2     True
dtype: bool

#for GeoPandas >=v0.6.0
s.isna()
0    False
1     True
2    False
dtype: bool

As today, I looked into the documentation and I did not find a specific method to remove empty geometries, if not "improvising" a solution. If anyone wants to contribute to this topic, please share.

2
  • Is this a comment or an answer to the question? Commented Mar 13, 2023 at 10:44
  • Comments are not Answers. Non-Answers are likely to be deleted by automated review. Please take the Tour to better understand our Q&A model.
    – Vince
    Commented Mar 15, 2023 at 16:51

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.