Python:如何使用Geopandas仅在特定边界中过滤点?

时间:2019-04-19 12:32:48

标签: python shapefile geopandas

我有一个带有一些点的shapefile。

import geopandas as gpd
from geopandas.tools import sjoin
import osmnx as ox

myShape = gpd.read_file('myShape.shp')
myShape.head(3)

geometry
0   POINT (-72.09513801999077 18.6526410972226)
1   POINT (-72.21044508038457 19.61039786418674)
2   POINT (-72.27903674995586 18.52939294725028)

然后我从开放的街道地图及其边界中提取了一个城市。我只想保留城市内的点。

这就是我在做什么:

city = ox.gdf_from_place('Paris', which_result=2)
city = gpd.GeoDataFrame(city)

myShapeTmp = myShape.copy()
for i in myShape.index:
    if (myShape['geometry'][i] in gdf['geometry']) == False:
        myShapeTmp = myShapeTmp.drop([i], axis=0)

但这需要永远。有其他方法吗?

2 个答案:

答案 0 :(得分:1)

我以这种方式解决了

city = ox.gdf_from_place('Paris', which_result = 2)
city = gpd.GeoDataFrame(city)
boundary = city.ix[0].geometry
myShapeTmp = school[myShape.geometry.within(boundary)]

答案 1 :(得分:0)

获取points in polygon的另一种方式可能是这样的:

我们创建具有以下内容的文件port_au_princ.csv

index,geometry
0,POINT(-72.09513801999077 18.6526410972226)
1,POINT(-72.21044508038457 19.61039786418674)
2,POINT(-72.27903674995586 18.52939294725028)

这是执行所有必要操作的代码。

import pandas as pd
import geopandas as gpd
from geopandas.tools import sjoin
import osmnx as ox
from shapely.wkt import loads

# get polygon of the city
city_pgon = ox.gdf_from_place('Port-au-Prince', which_result = 2)
# create a geoDataFrame out of it, set appropriate CRS
city_pgon = gpd.GeoDataFrame(city_pgon, crs={'init': 'epsg:4326'})
# read the file
pap = pd.read_csv('port_au_princ.csv', sep=',')
geometry = [loads(pt) for pt in pap['geometry']]  # prep geometry
# create geoDataFrame from `pap` dataframe
geo_pap = gpd.GeoDataFrame(pap, geometry=geometry, crs={'init': 'epsg:4326'})
pts_in_poly = gpd.sjoin(geo_pap, city_pgon, op='within', how='inner') # do spatial join

ax1 = city_pgon.plot()   # plot the polygon
geo_pap.plot(ax=ax1, color='red', zorder=5)         # plot red points
pts_in_poly.plot(ax=ax1, color='yellow', zorder=6)  # plot yellow point

情节将是:

point-in-poly

使用以下代码打印出pts_in_poly的一些信息:

print(pts_in_poly.index, pts_in_poly.geometry)

输出

Int64Index([2], dtype='int64') 2    POINT (-72.27903674995586 18.52939294725028)
Name: geometry, dtype: object