如何用Geopandas从波兰多边形区域筛选城市?
问题分析与解决方法
为什么contains方法全返回False?
你的代码存在两个核心问题:
- 索引对齐错误:筛选后的
world是仅含波兰的1行GeoDataFrame,world['geometry']是长度为1的GeoSeries;而cities['geometry']是包含大量城市的多行GeoSeries。直接调用contains时,Geopandas会按索引对齐两个Series,但两者索引无重叠,最终返回全False的结果。 - 未正确提取目标几何对象:你需要用波兰的单个多边形几何去检查所有城市点,而非用整个GeoSeries做逐元素匹配。
替代解决方案
方法1:修正contains用法
直接提取波兰的单个几何对象,通过apply遍历所有城市点做空间判断:
import geopandas # 读取数据集 world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) # 提取波兰的单个几何对象 poland_geom = world[world.name == 'Poland'].geometry.iloc[0] cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities')) # 筛选位于波兰境内的城市 poland_cities = cities[cities.geometry.apply(lambda point: poland_geom.contains(point))] print(poland_cities)
方法2:使用空间连接(推荐)
Geopandas的geopandas.sjoin()是处理空间筛选的高效方案,专门用于基于空间关系连接数据集:
import geopandas # 读取数据集 world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) poland = world[world.name == 'Poland'] cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities')) # 空间连接:筛选"within"波兰多边形的城市 poland_cities = geopandas.sjoin(cities, poland, how="inner", predicate='within') print(poland_cities)
注:
predicate参数可指定空间关系,除within外,还可使用contains(需交换两个数据集顺序)、intersects等。
内容的提问来源于stack exchange,提问作者Maciej
相关产品推荐
相关产品推荐

