gpt4 book ai didi

python - Geopandas 数据框指向多边形

转载 作者:行者123 更新时间:2023-12-01 23:01:41 26 4
gpt4 key购买 nike

我有一个 geopandas 数据框,由 id 和由 2D 点填充的几何列组成。我想连接每个唯一 id 的点来创建一个多边形,以便我的新数据框将多边形作为其几何形状。我的代码目前看起来像这样:

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"

这是有道理的,因为它仍然只是一个坐标列表,而不是一个实际的多边形对象。有谁知道如何使其成为一个实际的多边形对象,我可以将其添加到 geopandas 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()

enter image description here

关于python - Geopandas 数据框指向多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com