Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Geopandas set geometry: ValueError for MultiPolygon "equal len keys and value"

I have 2 geodataframes with a geometry column and I copy some geometries from 1 to the other.

This works well with Polygons but returns a ValueError for any (valid) MultiPolygon.

Please advice how to solve this? I don't know if / how / why I should change the MultiPolygon to get "equal len keys and value"?

geodata01.loc[index, 'geometry'] = geodata02.loc[index, 'geometry']

This works well with Polygons. Only with MultiPolygons I get:

ValueError 
if len(labels) != len(value):
--> 611      raise ValueError('Must have equal len keys and value '
    612      'when setting with an iterable')

I also cannot do assignments of a buffered or simplified MultiPolygon either (the MultiPolygon is valid and I can plot, buffer, simplify but I cannot assign it):

geodata01.loc[index, 'geometry'] = geodata01.loc[index, 'geometry'].buffer(0)
#or
geodata01.loc[index, 'geometry'] = geodata01.loc[index, 'geometry'].simplify(tolerance=0)

This returns the same ValueError.

like image 284
Wouter Avatar asked May 07 '19 08:05

Wouter


1 Answers

Explanation and workaround from the github issue as provided by Joris:

"The reason is that pandas checks the length of the value you want to assign, to see if it matches with the number of elements you are assigning to (here a single element, since the index is a scalar). So we might need to discuss this on the pandas side how to deal with that.

As a work-around, you can assign to a list of one element:

df.loc[[0], 'geometry'] = df.loc[[1], 'geometry'].values

Note that I also use a list to select the single element I want to assign, but then do .values, so I am basically assigning an array of one value (the problem is when not converting to an array, pandas will try to align on the index, and the assignment goes wrong). "

Many thanks again to Joris who provided the workaround and created a pandas issue to resolve this: REGR: assigning scalar with a length no longer works

like image 139
Wouter Avatar answered Nov 06 '22 13:11

Wouter