python - 如何使用 geopandas 有效地在多边形查询中做一个点?
问题描述
我有一个包含美国所有县的 shapefile,我在纬度/经度点进行了一堆查询,然后找到该点所在的县。现在我只是遍历所有县并执行 pnt .within(县)。这不是很有效。有一个更好的方法吗?
解决方案
您的情况看起来像是一个spatial joins
有用的典型案例。空间连接的想法是使用地理坐标而不是使用属性来合并数据。
中的三种可能性geopandas
:
intersects
within
contains
看起来像你想要within
的,这可以使用以下语法:
geopandas.sjoin(points, polygons, how="inner", op='within')
注意:您需要已安装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'))
countries = world[world['continent'] == "Europe"].rename(columns={'name':'country'})
countries.head(2)
pop_est continent country iso_a3 gdp_md_est geometry
18 142257519 Europe Russia RUS 3745000.0 MULTIPOLYGON (((178.725 71.099, 180.000 71.516...
21 5320045 Europe Norway -99 364700.0 MULTIPOLYGON (((15.143 79.674, 15.523 80.016, ...
cities.head(2)
name geometry
0 Vatican City POINT (12.45339 41.90328)
1 San Marino POINT (12.44177 43.93610)
cities
是一个全球数据集,countries
也是一个欧洲范围的数据集。
两个数据集都需要在同一个投影系统中。如果没有,请.to_crs
在合并前使用。
data_merged = geopandas.sjoin(cities, countries, how="inner", op='within')
最后,看看结果让我们做一个地图
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(5)
name geometry index_right pop_est continent country iso_a3 gdp_md_est
0 Vatican City POINT (12.45339 41.90328) 141 62137802 Europe Italy ITA 2221000.0
1 San Marino POINT (12.44177 43.93610) 141 62137802 Europe Italy ITA 2221000.0
192 Rome POINT (12.48131 41.89790) 141 62137802 Europe Italy ITA 2221000.0
2 Vaduz POINT (9.51667 47.13372) 114 8754413 Europe Austria AUT 416600.0
184 Vienna POINT (16.36469 48.20196) 114 8754413 Europe Austria AUT 416600.0
在这里,我使用inner
了 join 方法,但这是一个可以更改的参数,例如,如果您想保留所有点,包括不在多边形内的点。
推荐阅读
- sql - 将 SQL 查询限制为几个结果
- python - 如何使用 Python GUI 自定义按钮和文本框?
- arrays - 获取通过遍历数组找到的单元格的单元格引用?
- stripe-payments - 如果自动重试之一成功,条带是否会自动将订阅设置回“活动”?
- c++ - 是什么使这个以“+”开头的字符串添加成为有效语句?
- php - 如何使用 php artisan 执行 cron-job 命令?
- javascript - 使用自定义选项编写 Vue 插件
- encryption - 调用未定义的函数 blenc_encrypt()
- c++ - cgal多边形网格器中的tet网格密度分级
- html - 如何使用文件夹路径链接 html 中的图像?或者没有 Http 或 https