Python geopandas - 如何聚合(或进行其他一些统计)多边形内点的值?

Jan*_*nis 2 python statistics polygon spatial geopandas

我对 geopandas 有疑问,我自己无法想出一个聪明的解决方案......

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

有人可以为我提供一种快速通用的方法来用 python 进行编码吗?

我使用 Python 3.7 和 geopandas 0.7.0。

提前谢谢了!

lin*_*nog 5

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

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

您可以找到有关如何使用 inside 来选择落在某个地方(例如欧洲)的观察结果的答案

语法如下:

geopandas.sjoin(points, polygons, how="inner", op='within')
Run Code Online (Sandbox Code Playgroud)

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

例子

让我们合并城市和国家以及按大陆划分的合计值。

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'))
Run Code Online (Sandbox Code Playgroud)

我们在数据中创建一个虚拟变量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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)