【问题标题】:Join multiple Points to Polygon and concatenate joined point values of column into Polygon column将多个点连接到多边形并将列的连接点值连接到多边形列
【发布时间】:2018-03-19 01:07:28
【问题描述】:

我的数据:

Points:
    ID HN Street 
    1  5  Examplestreet
    2  6  Examplestreet
    3  2  Otherstreet
    4  2  Anotherstreet
Polygons:
    Name
    Firstpolygon
    Secondpolygon
    Otherpolygon  

所以我想执行一个(多边形)到多个(点)空间连接,并将连接的值从点 HN 列连接到 Polygonsfile 中的新列“all_HN”。

所以结果应该是这样的:

Name          all_HN
Firstpolygon  5,6   -> if the points ID1 and ID2 lie within the same polygon (`"Firstpolygon"`)
Secondpolygon 2     -> point ID3 within the `"Secondpolygon"`
Otherpolygon  NULL  -> no point within "Otherpolygon"
and so on

我想用 geopandas 解决这个问题。 (我有大约 200.000 个点和 100.000 个多边形) 使用以下代码:

from geopandas import gpd

points = gpd.GeoDataFrame.from_file('MyPointsFile) # or geojson etc 
polys = gpd.GeoDataFrame.from_file('MyPolygonsFile.shp') 
pointInPoly = gpd.sjoin(points, polys, op='within',how='inner')

现在我想使用类似的东西:

pointInPoly.groupby('index_right')['HN_left'].sum()

但正确的命令不是 sum(),而是将匹配点的所有值连接到一个新列“all_HN”中。

任何人,知道如何解决这个问题吗?使用另一个包而不是 geopandas 也可以。 由于 geopandas 基于 pandas,pandas 解决方案也应该可以工作。 只需将匹配项的所有列附加到相应的多边形表中就足够了。

【问题讨论】:

    标签: python pandas concatenation geospatial geopandas


    【解决方案1】:

    如果您想将这些值分组而不是将它们相加,您可以执行以下操作(使用没有几何图形的示例数据框,但merge 之后的结果而不是sjoin 应该是相似的):

    In [53]: df1 = pd.DataFrame({'key': ['a', 'b', 'c'], 'index': [1, 2, 3]})
    
    In [54]: df2 = pd.DataFrame({'key': ['a', 'a', 'b'], 'HN': [5, 6, 2]})
    
    In [55]: res = pd.merge(df1, df2, how='left')
    
    In [56]: res
    Out[56]: 
       index key   HN
    0      1   a  5.0
    1      1   a  6.0
    2      2   b  2.0
    3      3   c  NaN
    
    In [57]: res.groupby('index')['HN'].apply(list)
    Out[57]: 
    index
    1    [5.0, 6.0]
    2         [2.0]
    3         [nan]
    Name: HN, dtype: object
    

    如果您不想要[nan],您可以稍微调整一下传递给apply 的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      相关资源
      最近更新 更多