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

问题描述 投票:0回答:1

我遇到了有关Geopandas的问题,我自己无法提出一个明智的解决方案...

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

任何人都可以为我提供快速通用的python编码方法?

我使用Python 3.7和geopandas 0.7.0。

非常感谢!

python statistics polygon spatial geopandas
1个回答
0
投票

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

  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才能执行此类操作。如果需要安装此依赖项,请使用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'))

我们在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
© www.soinside.com 2019 - 2024. All rights reserved.