2

I try to create a shapefile of the FAO/GAUL/2015/leve1 country regions of the LMIC's countries. For that I decided to use Python as it gave me access to the earthengine API and the geopandas librairy.

To create the geodataframe I proceed as such :

import ee 
import geemap
import geopandas as gpd

ee.Initialize()

for i, row in df.iterrows():
    # select the country
    ee_country = ee.FeatureCollection("FAO/GAUL/2015/level1").filter(ee.Filter.eq('ADM0_CODE', row.GAUL))
    country_json = geemap.ee_to_geojson(ee_country)
    tmp = gpd.GeoDataFrame.from_features(country_json)
    
    # add the country to the global gdf 
    gdf = tmp if i == 0 else pd.concat([gdf, tmp])
 
gdf.crs = "EPSG:4326"
gdf

(the df is containing the FAO GAUL ADM0_CODE)

Then I try to transform this GDF into a shapefile using

gdf.to_file('FAO_GAUL_2015_level1.shp')

But I get an error because I have shapely.geometry.collection.GeometryCollection in my gdf (with linestring embed so not shapelyfiable).

Is there a way to only kee the Polygon for revery lin that contain a Geometry collection ? or Is it possible to drop all the linestring from the geometry column ?

3 Answers 3

1

I created a workaround that replace each line of the gdf containing a geometryCollection (a linestring + a polygon) by its first polygon

You can customize it to better fit your requirements

gdf_filtered = gdf.copy()

for i, row in gdf.iterrows():
    if type(row.geometry) == shapely.geometry.collection.GeometryCollection:

        # get the polygon and only keep the polygon 
        for shape in row.geometry:
            if type(shape) == shapely.geometry.polygon.Polygon:
                gdf_filtered.at[i, 'geometry'] = shape
                break
0

As per the answer, but if you want all polygons rather than just one then use:

gdf_filtered = gdf.copy()

for i, row in gdf.iterrows():
    if type(row.geometry) == shapely.geometry.collection.GeometryCollection:

        # get all polygons
        shapes = []
        for shape in row.geometry:
            if type(shape) == shapely.geometry.polygon.Polygon:
                shapes.append(shape)
        gdf_filtered.at[i, 'geometry'] = shapely.geometry.collection.GeometryCollection(shapes)
0

You can drop all LineStrings from the geometry column like this:

gdf = gdf[gdf.geometry.type != 'LineString']

If you want to split multipart geometries into single part geometries use

gdf.explode()

Your Answer

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

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