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

问题描述 投票:0回答:2

我有一个带有一些点的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)

但它需要永远。有不同的方法吗?

python shapefile geopandas
2个回答
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)]

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
© www.soinside.com 2019 - 2024. All rights reserved.