0

I'm working on some real world geometric data using GeoPandas, which relies on Pandas.

I don't really care about the index in my GeoDataFrame (it has been assigned automatically) but when it comes to updating a single cell based on a condition in one or more specific columns (instead of the index), in the following example, a building Identifier column, I wish I can benefit from the .at operator as explained here or there.

For the moment, I'm extracting the index value where my condition is met to be able to use .at method:

# gdf is a GeoDataFrame
gdf.at[gdf[gdf['Identifier'] == mybuilding.identifier].index.values[0], 'geometry'] = gpd.GeoSeries([shape]).iloc[0]

The gdf[gdf['Identifier'] == mybuilding.identifier].index.values[0] part is only used to extract the index properly for the .at method to work.

Otherwise, if I'm using the .loc method, the column I want to update is not updated (and I don't know why, because it should work...):

gdf.loc[gdf['Identifier'] == mybuilding.identifier, 'geometry'] = gpd.GeoSeries([shape])

and the following raises the error ValueError: Must have equal len keys and value when setting with an iterable:

gdf.loc[gdf['Identifier'] == mybuilding.identifier, 'geometry'] = gpd.GeoSeries([shape]).iloc[0]

(shape is a Shapely MultiPolygon instance)

Is there a more pythonic (but still efficient) way to go?
Because if the first solution is actually working, it's rather cumbersome to write...

An SQL equivalent would be:

UPDATE geodataframe SET "geometry" = <shape> WHERE "Indentifier" = mybuilding_indentifier;

Version info:
GeoPandas: '0.12.1'
Pandas: '1.5.1'
Shapely: '1.8.5.post1'
Python: 3.10.6

If I have missed a duplicate, I will delete my question if I am pointed to an existing working solution with clear explanations.

swiss_knight
  • 5,787
  • 8
  • 50
  • 92
  • Hi, what does `gpd.GeoSeries([shape])` look like? – Laurent Dec 03 '22 at 14:58
  • It's a `geopandas.geoseries.GeoSeries` instance containing a single Polygon: `0 POLYGON (((706331.272 320147.755 456.... dtype: geometry` In some other cases it's a single `MULTIPOLYGON`. Nothing fancy here. – swiss_knight Dec 03 '22 at 20:14

0 Answers0