簡體   English   中英

如何轉換pandas中的lat / lon點並查看它們是否屬於某些邊界多邊形?

[英]How to convert lat/lon points in pandas and see whether they fall in some boundary polygons?

我有一個熊貓數據幀df是這樣的:

 id   lat  lon
 jhg  2.7  3.5
 ytr  3.1  3.5
 ...

我也有一個Geopandas數據幀poly一些多邊形。 現在,我想只繪制一些多邊形內的 df點。 所以我應該能夠做像poly.intersects(p)這樣的事情,其中p是一個Shapely Point 但我做錯了;

from shapely.geometry import Point
for index, row in df.iterrows():
    t = poly.intersects(Point(row.lon, row.lat))

傳遞具有lat / lon點的數據幀並將其覆蓋到poly的最佳方法是什么? 請注意,我可以定義最小/最大緯度/經度范圍,但也可以在poly外部打印點,但在(較大的)邊界框內打印。

你的出發點:

import pandas as pd
from shapely.geometry import box
import matplotlib.pyplot as plt

from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
from shapely.geometry import Point
import seaborn as sns
import numpy as np

# some pretend data
data = {'lat':[2.7,3.5,1.4,2.3,.9,1.9], 'lon':[1.2,.9,1.9,2.2,3,1.1]}
df = pd.DataFrame(data)

# the 'bounding' polygon
poly = box(1,1,2,2)
patches  = PatchCollection([Polygon(poly.exterior)], facecolor='red', linewidth=.5, alpha=.5)


# plot the bounding box 
fig, ax = sns.plt.subplots(1, figsize=(4,4))
ax.add_collection(patches, autolim=True)

# plot the lat/lon points
df.plot(x='lat',y='lon', kind='scatter',ax=ax)
plt.show()

這些數字看起來像這樣:

在此輸入圖像描述

擺脫不需要的點的一種方法是使用布爾掩碼:

#probably more efficient ways to do this, but this works
mask = [poly.intersects(Point(lat,lon)) for lat,lon in zip(df.lat,df.lon)]
df = df[mask]

# make new plot (must make a new 'patch' object)
patches1  = PatchCollection([Polygon(poly.exterior)], facecolor='red', linewidth=.5, alpha=.5)
fig1, ax1 = sns.plt.subplots(1, figsize=(4,4))
ax1.add_collection(patches1, autolim=True)

# make the axis bounds the same
ax1.set_xlim(ax.get_xlim())
ax1.set_ylim(ax.get_ylim())

# plot the lat/lon points
df.plot(x='lat',y='lon', kind='scatter',ax=ax1)
plt.show()

給我這個形象。

在此輸入圖像描述

請注意,您可以使用其他更快的方式創建布爾掩碼,例如lat是否位於多邊形中的最高點之上。 那些可能不是完美的,但可以減少問題,所以你沒有多次調用intersects()

[編輯:如果您的多邊形是一個矩形,]另一種方式(正如您在問題中所建議的那樣)將只是圍繞邊界多邊形“裁剪”圖像。 這是一個更快的解決方案,因為您不必一遍又一遍地調用intersects()函數。 要根據邊界多邊形修剪圖像,可以在plt.plot()之前插入此權限:

ax.set_xlim((np.min(poly.exterior.xy[0]),np.max(poly.exterior.xy[0])) )
ax.set_ylim((np.min(poly.exterior.xy[1]),np.max(poly.exterior.xy[1])) )

給出以下內容:

在此輸入圖像描述

本教程似乎可以滿足您的需求。 它還利用了geopandas內置的Rtree空間索引來實現快速交叉查詢。

spatial_index = gdf.sindex
possible_matches_index = list(spatial_index.intersection(polygon.bounds))
possible_matches = gdf.iloc[possible_matches_index]
precise_matches = possible_matches[possible_matches.intersects(polygon)]

然后它將多邊形及其內部和外部的點繪制成不同的顏色,就像您想要的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM