[英]How to do a point in polygon query efficiently using geopandas?
我有一個包含美國所有縣的 shapefile,我在緯度/經度點進行了一堆查詢,然后找到該點所在的縣。現在我只是遍歷所有縣並執行 pnt .within(縣)。 這不是很有效。 有一個更好的方法嗎?
您的情況看起來像是spatial joins
很有用的典型情況。 空間連接的想法是使用地理坐標而不是使用屬性來合並數據。
geopandas
中的三種可能性:
intersects
within
contains
似乎您想要within
,可以使用以下語法:
geopandas.sjoin(points, polygons, how="inner", op='within')
注意:您需要安裝rtree
才能執行此類操作。 如果需要安裝這個依賴,使用pip
或者conda
安裝
例如,讓我們 plot 歐洲城市。 兩個示例數據集是
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')
最后,看看結果讓我們做一個 map
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
連接方法,但如果您想保留所有點,包括不在多邊形內的點,您可以更改該參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.