2017-09-15 35 views
0

扩大MULTIPOLYGON我有一个包含两个多边形和multipolygons如下shape文件:在geopanda数据帧

name           geometry 
0 AB10 POLYGON ((-2.116454759005259 57.14656265903432... 
1 AB11 (POLYGON ((-2.052573095588467 57.1342600856536... 
2 AB12 (POLYGON ((-2.128066321470298 57.0368357386797... 
3 AB13 POLYGON ((-2.261525922489881 57.10693578217748... 
4 AB14 POLYGON ((-2.261525922489879 57.10693578217748... 

的第二和第三排对应组合区,而其余的都是多边形。 我想将几何图形为Multipolygon类型的行扩展为Polygon行,如下所示。

name           geometry 
0 AB10 POLYGON ((-2.116454759005259 57.14656265903432... 
1 AB11 POLYGON ((-2.052573095588467 57.1342600856536... 
2 AB11 POLYGON ((-2.045849648028651 57.13076387483844... 
3 AB12 POLYGON ((-2.128066321470298 57.0368357386797... 
4 AB12 POLYGON ((-2.096125852304303 57.14808092585477 
3 AB13 POLYGON ((-2.261525922489881 57.10693578217748... 
4 AB14 POLYGON ((-2.261525922489879 57.10693578217748... 

请注意,AB11和AB12 Multipolygon已扩展为多行,其中每行对应一个多边形数据。

我认为这是geopanda数据处理。有没有一种pythonic的方式来实现上述?

谢谢!

+0

这不会是没有非常有帮助一些上下文或一些代码来重现实际的数据帧。 –

回答

0

我目前的解决方案是双倍的。

第1步。遍历每一行,如果类型是多面体,则应用列表理解。

name           geometry 
0 AB10 POLYGON ((-2.116454759005259 57.14656265903432... 
1 AB11 [POLYGON ((-2.052573095588467 57.1342600856536... 
2 AB12 [POLYGON ((-2.128066321470298 57.0368357386797... 
3 AB13 POLYGON ((-2.261525922489881 57.10693578217748... 
4 AB14 POLYGON ((-2.261525922489879 57.10693578217748... 

第2步:使用将一行中元素列表扩展到多行的技巧。

df.set_index(['name'])['geometry'].apply(pd.Series).stack().reset_index() 

    name level_1             0 
0 AB10  0 POLYGON ((-2.116454759005259 57.14656265903432... 
1 AB11  0 POLYGON ((-2.052573095588467 57.13426008565365... 
2 AB11  1 POLYGON ((-2.045849648028651 57.13076387483844... 
3 AB12  0 POLYGON ((-2.128066321470298 57.0368357386797,... 
4 AB12  1 POLYGON ((-2.096125852304303 57.14808092585477... 
5 AB13  0 POLYGON ((-2.261525922489881 57.10693578217748... 
6 AB14  0 POLYGON ((-2.261525922489879 57.10693578217748... 

请让我知道是否有办法做到这一步!

0

如果您只有两列,我们可以使用numpy来提高速度。

如果你有一个像

 
    name    geometry 
0  0    polygn(x) 
1  2 (polygn(x), polygn(x)) 
2  3    polygn(x) 
3  4 (polygn(x), polygn(x)) 

一个数据帧然后numpy的meshgrid将有助于

def cartesian(x): 
    return np.vstack(np.array([np.array(np.meshgrid(*i)).T.reshape(-1,2) for i in x.values])) 

ndf = pd.DataFrame(cartesian(df),columns=df.columns) 

输出:

 
    name geometry 
0 0 polygn(x) 
1 2 polygn(x) 
2 2 polygn(x) 
3 3 polygn(x) 
4 4 polygn(x) 
5 4 polygn(x) 
%%timeit 
ndf = pd.DataFrame(cartesian(df),columns=df.columns) 

1000 loops, best of 3: 679 µs per loop 

%%timeit 
df.set_index(['name'])['geometry'].apply(pd.Series).stack().reset_index() 

100 loops, best of 3: 5.44 ms per loop