TransWikia.com

GeoPandas setting geometry for a row with .loc and Multipolygons

Geographic Information Systems Asked by Thagor on January 10, 2021

Given the following example:

def merge_with_largest(input_gdf,poly):
    
    # select the polygons bordering polygon
    close_by_gdf = input_gdf[input_gdf.geometry.intersects(poly)]
    # selects the index of the row with the largest area
    selected_index = close_by_gdf['area'].argmax()
    # now we merge the geometry of the selected index with the polygon geometry
    selected_geom = input_gdf.loc[selected_index]['geometry']
    # setting the 
    input_gdf.loc[selected_index,['geometry']] = gpd.GeoSeries((selected_geom,poly)).unary_union

What I want to do here is to merge the geometry of poly with the largest of the polygons that do intersect it with. I want to do this by using .unary_union between the two selected polygons and then update the geometry of the selected polygon with what .unary_union returns. The problem though is that sometimes .unary_union returns a mulitpolygon and then the .loc method throws an error because it’s an iterable.

ValueError: Must have equal len keys and value when setting with an iterable

Is there a way to overwrite this and set the multipolygon as the the geometry for the selected column?

One Answer

I found a workaround to my problem credit here goes to github https://github.com/geopandas/geopandas/issues/992

the solution in a nutshell:

geom = df.loc[1, 'geometry']
df.loc[[0], 'geometry'] = geopandas.GeoSeries([geom])

if geom is a multipolygon we cast it into a GeoSeries and then set the series as the new geometry

Answered by Thagor on January 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP