我认为此时您可以拥有的最佳工作流程是
- 空间连接将您的点与它们所属的多边形相匹配
-
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