Geopandas Dataframe指向多边形
问题描述:
我有一个由一个id和一个由2D点填充的几何列组成的geopandas数据框。我想加入每个唯一ID的点来创建一个多边形,以便我的新数据框将具有多边形作为其几何。我的代码目前看起来是这样的:Geopandas Dataframe指向多边形
polygons = geopandas.GeoDataFrame()
for i in id:
group = df[df['id']== i]
polygon = {'type': 'Polygon', 'coordinates': group['geometry']}
polygon['poly'] = polygon
polygons = geopandas.concat([polygon,polygons])
它创建了一个多边形,但是当我分配一个新的变量poly
它说
ValueError: Length of values does not match length of index"
这是有道理的,因为它仍然只是一个坐标,而不是名单一个实际的多边形对象。有谁知道如何让这个实际的多边形对象,我可以添加到一个地域和列上的列df
?
在此先感谢:)
答
我已经实现了与groupby
函数类似的东西。假设你的点实际上是Shapely Point
对象,并按正确的顺序排序,你可以尝试这样的事情。
import pandas as pd
import geopandas as gp
from shapely.geometry import Point, Polygon
# Initialize a test GeoDataFrame where geometry is a list of points
df = gp.GeoDataFrame([['box', Point(1, 0)],
['box', Point(1, 1)],
['box', Point(2,2)],
['box', Point(1,2)],
['triangle', Point(1, 1)],
['triangle', Point(2,2)],
['triangle', Point(3,1)]],
columns = ['shape_id', 'geometry'],
geometry='geometry')
# Extract the coordinates from the Point object
df['geometry'] = df['geometry'].apply(lambda x: x.coords[0])
# Group by shape ID
# 1. Get all of the coordinates for that ID as a list
# 2. Convert that list to a Polygon
df = df.groupby('shape_id')['geometry'].apply(lambda x: Polygon(x.tolist())).reset_index()
# Declare the result as a new a GeoDataFrame
df = gp.GeoDataFrame(df, geometry = 'geometry')
df.plot()
答
大答案@ atkat12。但是,根据您的情节,最后两个箱点应该在(0,1)和(0,0):
# Initialize a test GeoDataFrame where geometry is a list of points df = gp.GeoDataFrame([['box', Point(1, 0)], ['box', Point(1, 1)], ['box', Point(0,1)], ['box', Point(0,0)], ['triangle', Point(1, 1)], ['triangle', Point(2,2)], ['triangle', Point(3,1)]], columns = ['shape_id', 'geometry'], geometry='geometry')