axb2035
axb2035

Reputation: 73

Trying to assign two polygon elements from a multipolygon to geopandas geometry column causes ValueError

I'm using the geopandas built in world map. I'm trying to split out French Guiana from the France geometry and create a new entry for French Guiana (which I have done successfully). However, when reassinging the reduced European France and Corsica multi-polygon back to the France geometry cell I get an error.

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# Remove French Guiana (shape[0])
shape = world[world['name'] == 'France']['geometry'].all()

fr_shape = shape[2] # This works creating a POLYGON but drops Corsica :( 
world.at[world['name'] == 'France', 'geometry'] = fr_shape

fr_shape = shape[1:] # This creates a MULTIPOLYGON then throws an ValueError.
world.at[world['name'] == 'France', 'geometry'] = fr_shape

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

It's a similar problem to here: Geopandas set geometry: ValueError for MultiPolygon "equal len keys and value"

However, as I'm trying to extract two of the three elements of the multipolygon and reassign, to me seem like a different problem as the other is a straight copy from one dataframe to another without manipulation. Trying various variations of the .values solution has not been successful to date throwing the same problem.

Upvotes: 1

Views: 565

Answers (1)

axb2035
axb2035

Reputation: 73

I've managed to find a workaround:

import pandas as pd
import geopandas as gpd

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# Remove French Guiana from France.
shape = world[world['name'] == 'France']['geometry'].all()

# Multipolygon ValueError Workaround.
fr_df = pd.Series(['France', 'France'], name='country')
fr_df = gpd.GeoDataFrame(fr_df, geometry=[shape[1], shape[2]])
fr_df = fr_df.dissolve(by='country')
world.at[world['name'] == 'France', 'geometry'] = fr_df['geometry'].values                     

world.plot()

Upvotes: 2

Related Questions