2016-11-28 93 views
1

我想在shapefile的多邊形內找到一個點。如何在多邊形內找到點?

我需要寫一個循環,可以遍歷的多邊形,並返回其中點位於多邊形的指數。

我怎麼會寫一個循環來找出哪些多邊形點是?

這裏是我迄今寫的:

import pandas as pd 
import pylab as pl 
import os 
import zipfile 
import geopandas as gp 
import shapely 

%pylab inline 

# Read in the shapefile 
ct_shape = gp.read_file(path) 

# Segmented the file so it only contains Brooklyn data & set projection 
ct_latlon = ct_shape[ct_shape.BoroName == 'Brooklyn'] 
ct_latlon = ct_latlon.to_crs({'init': 'epsg:4326'}) 
ct_latlon.head() 

# Dataframe image 
[Head of the dataframe image][1]: https://i.stack.imgur.com/xAl6m.png 


# Created a point that I need to look for within the shapefile 
CUSP = shapely.geometry.Point(40.693217, -73.986403) 

輸出可以是這樣的:「3001100」(在正確的多邊形的BCTCB2010)

+0

問題是什麼?我在你的文章中沒有看到問題,也沒有描述你正在掙扎的內容。 –

+0

@OliverW。我需要編寫一個可以找到多邊形內點的索引的循環。 –

+0

假設總共有N條邊。你可以使用一個解決方案,依次嘗試每個多邊形,總工作量爲O(N),或者你想要更高效,比如O(log(N)+ K),其中K是橫過水平線的邊的數量? (經過一些預處理。) –

回答

1

我解決了它的一行代碼。沒有必要的循環。

過帳其他人可能有興趣:

# Setting the coordinates for the point 
CUSP = shapely.geometry.Point((-73.986403, 40.693217,)) # Longitude & Latitude 

# Printing a list of the coords to ensure iterable 
list(CUSP.coords) 

# Searching for the geometry that intersects the point. Returning the index for the appropriate polygon. 
index = ct_latlon[ct_latlon.geometry.intersects(CUSP)].BCTCB2010.values[0] 
0

我會用GeoDataFrame sjoin

下面是一個簡單的例子,我有相當於巴黎的座標一個城市,我會嘗試與一個國家,在各國家GeoDataFrame匹配。

import geopandas as gpd 
from shapely.geometry.point import Point 

# load a countries GeoDataFrame given in GeoPandas 
countries = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))\ 
       .rename(columns={"name":"country_name"}) 

#making a GeoDataFrame with your city 
paris = Point(2.35, 48.85) 
cities = gpd.GeoDataFrame([{"city" : "Paris", "geometry":paris} ]) 

In [33]: cities 
Out[33]: 
    city   geometry 
0 Paris POINT (2.35 48.85) 

#now we left_join cities and countries GeoDataFrames with the operator "within" 

merging = gpd.sjoin(cities, countries, how="left", op="within") 

In [34]: merging 
Out[34]: 
    city   geometry index_right continent gdp_md_est iso_a3 \ 
0 Paris POINT (2.35 48.85)   55 Europe 2128000.0 FRA 

    country_name  pop_est 
0  France 64057792.0 

我們看到,巴黎Point已經在countries GeoDataFrame這是法國發現該國的多邊形內部的指標55:

In [32]: countries.loc[55] 
Out[32]: 
continent             Europe 
gdp_md_est            2.128e+06 
geometry  (POLYGON ((-52.55642473001839 2.50470530843705... 
iso_a3              FRA 
country_name            France 
pop_est            6.40578e+07 
Name: 55, dtype: object 

因此,如果你有個列表而不只是一個,你只需要創建一個更大的cities GeoDataFrame。

0

東西可能會感興趣的,除了你接受的回答:還可以採取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)] 

this tutorial。該示例返回哪些點與單個多邊形相交,但您可以輕鬆地將其適用於具有多個多邊形的單點示例。

相關問題