아래 코드를 사용하여 수백만 개의 GPS 포인트가있는 국가 (및 때로는 주)를 찾습니다. 코드는 현재 포인트 당 약 1 초가 걸리며 매우 느립니다. shapefile은 6MB입니다.
geopandas는 공간 조인에 rtree를 사용하여 매우 효율적으로 만들지 만 여기서는 작동하지 않는 것 같습니다. 내가 뭘 잘못하고 있죠? 나는 초당 천 점 정도를 바라고 있었다.
shapefile 및 csv는 여기 (5MB)에서 다운로드 할 수 있습니다. https://www.dropbox.com/s/gdkxtpqupj0sidm/SpatialJoin.zip?dl=0
import pandas as pd
import geopandas as gpd
from geopandas import GeoDataFrame, read_file
from geopandas.tools import sjoin
from shapely.geometry import Point, mapping,shape
import time
#parameters
shapefile="K:/.../Shapefiles/Used/World.shp"
df=pd.read_csv("K:/.../output2.csv",index_col=None,nrows=20)# Limit to 20 rows for testing
if __name__=="__main__":
start=time.time()
df['geometry'] = df.apply(lambda z: Point(z.Longitude, z.Latitude), axis=1)
PointsGeodataframe = gpd.GeoDataFrame(df)
PolygonsGeodataframe = gpd.GeoDataFrame.from_file(shapefile)
PointsGeodataframe.crs = PolygonsGeodataframe.crs
print time.time()-start
merged=sjoin(PointsGeodataframe, PolygonsGeodataframe, how='left')
print time.time()-start
merged.to_csv("K:/01. Personal/04. Models/10. Location/output.csv",index=None)
print time.time()-start
답변
sjoin 함수에 op = ‘within’인수를 추가하면 다각형 내 작업 속도가 크게 향상됩니다.
기본값은 op = ‘intersects’이며 올바른 결과로 이어지지 만 100 ~ 1000 배 느립니다.
답변
이 질문은 geopandas 공간 조인에서 r-tree를 활용하는 방법을 묻고 다른 응답자는 ‘교차’대신 ‘내부’를 사용해야한다고 올바르게 지적합니다. 그러나이 geopandas r-tree 자습서 에서 설명한대로 intersects
/ 를 사용하는 동안 geopandas에서 r-tree 공간 인덱스를 활용할 수도 있습니다 .intersection
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)]
답변
여기서 일어날 가능성은 오른쪽의 데이터 프레임 만 rtree 인덱스에 공급된다는
것입니다 .
https://github.com/geopandas/geopandas/blob/master/geopandas/tools/sjoin.py#L48-L55op="intersects"
run은 폴리곤이 인덱스에 공급되었음을 의미하므로 모든 포인트에 대해 rtree 인덱스를 통해 해당 폴리곤이 발견됩니다.
그러나의 op="within"
경우 작업이 실제로 역수이기 때문에 지오 데이터 프레임이 뒤집 힙니다 contains
:
https://github.com/geopandas/geopandas/blob/master/geopandas/tools/sjoin.py#L41-L43
op
에서 op="intersects"
를 전환 할 때 일어난 일은 op="within"
모든 다각형에 대해 rtree 인덱스를 통해 해당 지점을 찾은 것입니다.