2016-08-23 93 views
0

我有一個由一個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
在此先感謝:)

回答

1

我已經實現了與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

0

大答案@ 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')