首页 > 解决方案 > 如何使用 geopandas 有效地在多边形查询中做一个点?

问题描述

我有一个包含美国所有县的 shapefile,我在纬度/经度点进行了一堆查询,然后找到该点所在的县。现在我只是遍历所有县并执行 pnt .within(县)。这不是很有效。有一个更好的方法吗?

标签: pythongeopandas

解决方案


您的情况看起来像是一个spatial joins有用的典型案例。空间连接的想法是使用地理坐标而不是使用属性来合并数据。

中的三种可能性geopandas

  • intersects
  • within
  • contains

看起来像你想要within的,这可以使用以下语法:

geopandas.sjoin(points, polygons, how="inner", op='within')

注意:您需要已安装rtree才能执行此类操作。如果您需要安装此依赖项,请使用pipconda安装它

例子

例如,让我们绘制欧洲城市。两个示例数据集是

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 方法,但这是一个可以更改的参数,例如,如果您想保留所有点,包括不在多边形内的点。


推荐阅读