Skip to content

Instantly share code, notes, and snippets.

@acanalesg
Created November 21, 2013 17:42
Show Gist options
  • Save acanalesg/7586140 to your computer and use it in GitHub Desktop.
Save acanalesg/7586140 to your computer and use it in GitHub Desktop.
Back to the problem of determining in which polygon from a set of polygons is a list of points (see points_in_polygons1.py). Now we use shapely ... it is amazingly faster than the other approach
import pandas as pd
from shapely.geometry import Polygon, Point
# Read polygons from shapefile
provinces = shapefile.Reader("/data/geobrowsing/spain_gis/SHP_WGS84_PROVINCIAS_SIMPLE/PROVINCIAS_SIMPLE_OK.shp")
# Store as shapely Polygons along with the data for each of them
provs = list()
for sr in provinces.shapeRecords():
provs.append(sr.record + [Polygon(sr.shape.points),] )
#print sr.record
#[2, '02', 'Albacete']
#res = pip(test_point, sr.shape.points)
#print str(res) + "->" + str(sr.record) + str(len(sr.shape.points)) + "__" + str(sr.shape.bbox)
# Read points from csvfile
ucr = pd.read_csv('/data/geobrowsing/ES_UCR20130926.csv', header=None,
names=['cellid', 'lat', 'lon', 'height', 'centlat', 'centlon', 'zipcode', 'tech', 'type', 'freq', 'beam', 'azimuth'])
# Store them as shapely Points
points = list()
for u in ucr[['cellid', 'lon', 'lat']].values:
points.append(list(u) + [Point(u[1:3]), ])
# Loop over points and then over polygons to determine in which one is each point
#strlist = list()
for a in points:
for prov in provs:
if a[3].within(prov[3]):
#strlist.append(str(a) + " is in " + str(prov))
print str(a[0:3]) + " is in " + str(prov[0:3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment