2016-11-28 97 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。该示例返回哪些点与单个多边形相交,但您可以轻松地将其适用于具有多个多边形的单点示例。

相关问题