【问题标题】:Python geopandas - how to aggregate (or do some other statistics) values of points within a polygon?Python geopandas - 如何聚合(或做一些其他统计)多边形内的点值?
【发布时间】:2020-04-16 19:28:54
【问题描述】:

我对 geopandas 有疑问,我自己无法提出明智的解决方案...

我确实有两个 geopandas 数据框。一个包含点几何(例如城市),另一个包含多边形几何(例如国家)。每个点都有一个值(例如公民),我想确定多边形内的公民总数。它们都有相同的 CRS。

谁能为我提供一种快速且通用的方式在 python 中编写代码?

我使用 Python 3.7 和 geopandas 0.7.0。

非常感谢!

【问题讨论】:

    标签: python statistics polygon spatial geopandas


    【解决方案1】:

    我认为此时您可以拥有的最佳工作流程是

    1. 空间连接将您的点与它们所属的多边形相匹配
    2. groupby 你的多边形 ID 和 agg('sum')

    你可以找到这个answer on how to use within to select observations that fall somewhere, e.g. in Europe

    语法如下:

    geopandas.sjoin(points, polygons, how="inner", op='within')
    

    注意:您需要安装rtree 才能执行此类操作。如果需要安装这个依赖,使用pip或者conda来安装

    示例

    让我们在城市和国家之间进行合并,并按大陆汇总价值。

    import geopandas
    import numpy as np
    
    world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
    cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
    

    我们在cities 数据中创建一个虚拟变量:

    cities['pop'] = np.random.randint(1, 6, cities.shape[0])
    
    cities.head(3)
        name            geometry    pop
    0   Vatican City    POINT (12.45339 41.90328)   4
    1   San Marino      POINT (12.44177 43.93610)   1
    2   Vaduz           POINT (9.51667 47.13372)    1
    

    使用上面给出的方法执行空间连接:

    data_merged = geopandas.sjoin(cities, world, how="inner", op='within')
    
    data_merged.head(2)
        name_left   geometry    pop     index_right     pop_est     continent   name_right  iso_a3  gdp_md_est
    0   Vatican City    POINT (12.45339 41.90328)   4   141     62137802    Europe  Italy   ITA     2221000.0
    1   San Marino  POINT (12.44177 43.93610)   1   141     62137802    Europe  Italy   ITA     2221000.0
    

    请注意,例如,如果您想绘图,您最终会得到一个 point geopandas 对象。

    然后,您可以使用标准 pandas 语法来计算您的点数据的统计信息

    data_merged.groupby('continent').agg('sum')
    
        pop     index_right     pop_est     gdp_md_est
    continent               
    Africa  153     3430    1471168898  8227904.00
    Asia    129     4761    4462705033  56109347.77
    Europe  125     5392    1013640800  35541477.00
    North America   47  587     569302584   23362898.00
    Oceania     12  415     36220960    1401392.00
    South America   23  494     426315904   6381910.00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2019-03-07
      • 2022-01-22
      相关资源
      最近更新 更多