I have a dataframe with a column 'geometry', with either a MultiPolygon or a Polygon with this structure:
"{""coordinates"": [[[[7.550173037853544, 53.67503770572817], [7.547448703728663, 53.67578543283669], [7.546742188094777, 53.674936990272656], [7.544119530708709, 53.67559257263587], [7.539340754839757, 53.67377737266573]]]], ""type"": ""Polygon""}"
"{""coordinates"": [[[[7.550173037853544, 53.67503770572817], [7.547448703728663, 53.67578543283669], [7.546742188094777, 53.674936990272656], [7.544119530708709, 53.67559257263587], [7.539340754839757, 53.67377737266573]]]], ""type"": ""MultiPolygon""}"
(these are only parts of the entries, they would be too long to post).
Im trying to convert the whole DataFrame to a geodataframe, but im struggling.
What I did is delete all strings in the column and only leave the coordinates. Then I converted the columns to Polygons with this function:
def polygons_from_custom_xy_string(df_column):
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
def xy_list_from_string(s):
# 'x y x y ...' -> [[x, y], [x, y], ...]
return list(chunks([float(i) for i in s.split()], 2))
def poly(s):
""" returns shapely polygon from point list"""
ps = xy_list_from_string(s)
return Polygon([[p[0], p[1]] for p in ps])
polygons = [poly(r) for r in df_column]
gemeinde['geometry'] = polygons_from_custom_xy_string(gemeinde['geometry'])
gemeinde = gpd.GeoDataFrame(gemeinde, geometry='geometry')
I can plot it like that, but all my MultiPolygons break. Is there an easier way to just convert all the shapes to the corresponding shape?
I also tried this, but it doesnt work:
gemeinde['geometry'] = gemeinde['geometry'].apply(wkt.loads)
with the error: WKTReadingError: Could not create geometry because of errors while reading input. Is my file broken? In all the other threads I saw that the ""type"": ""MultiPolygon"" part is at the beginning, not the end of the cell.
Any help is much appreciated, Im a bit lost here.