2016-08-23 4 views
0

私はジオパンダのデータフレームにIDとジオメトリの列で構成され、2次元の点でデータが取り込まれています。各ユニーク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の列に追加できる実際のポリゴンオブジェクトにする方法を知っていますか?
ありがとうございます。

答えて

1

私はgroupby機能と同様のことを達成しました。あなたのポイントがShapely Pointオブジェクトで、正しい順序でソートされていると仮定すると、このようなことを試すことができます。 atkat12 @

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

偉大な答え。しかし、あなたのプロットによると、最後の二つの箱ポイントは(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') 
関連する問題