部分答案,取自我之前的另一个答案that needed within rather than contains
您的情况看起来像是spatial joins 有用的典型情况。空间连接的想法是使用地理坐标而不是使用属性来合并数据。
geopandas中的三种可能:
intersects
within
contains
您似乎想要contains,可以使用以下语法:
geopandas.sjoin(polygons, points, how="inner", op='contains')
注意:您需要安装rtree 才能执行此类操作。如果需要安装这个依赖,使用pip或者conda来安装
示例
作为示例,让我们随机抽取城市样本并绘制相关的国家/地区。这两个示例数据集是
import geopandas
import matplotlib.pyplot as plt
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
cities = cities.sample(n=50, random_state=1)
world.head(2)
pop_est continent name iso_a3 gdp_md_est geometry
0 920938 Oceania Fiji FJI 8374.0 MULTIPOLYGON (((180.00000 -16.06713, 180.00000...
1 53950935 Africa Tanzania TZA 150600.0 POLYGON ((33.90371 -0.95000, 34.07262 -1.05982...
cities.head(3)
name geometry
196 Bogota POINT (-74.08529 4.59837)
95 Tbilisi POINT (44.78885 41.72696)
173 Seoul POINT (126.99779 37.56829)
world 是一个全球数据集,cities 是一个子集。
两个数据集需要在同一个投影系统中。如果没有,请在合并前使用.to_crs。
data_merged = geopandas.sjoin(countries, cities, how="inner", op='contains')
最后,看看结果,让我们做一张地图
f, ax = plt.subplots(1, figsize=(20,10))
data_merged.plot(axes=ax)
countries.plot(axes=ax, alpha=0.25, linewidth=0.1)
plt.show()
并且底层数据集将我们需要的信息合并在一起
data_merged.head(2)
pop_est continent name_left iso_a3 gdp_md_est geometry index_right name_right
7 6909701 Oceania Papua New Guinea PNG 28020.0 MULTIPOLYGON (((141.00021 -2.60015, 142.73525 ... 59 Port Moresby
9 44293293 South America Argentina ARG 879400.0 MULTIPOLYGON (((-68.63401 -52.63637, -68.25000... 182 Buenos Aires
在这里,我使用了inner 连接方法,但如果您想保留所有点,包括不在多边形内的点,您可以更改该参数。