Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which points intersect with a polygon in geopandas?

I've been trying to use the "intersects" feature on a geodataframe, looking to see which points lie inside a polygon. However, only the first feature in the frame will return as true. What am I doing wrong?

from geopandas.geoseries import *

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

g1 = GeoSeries([p1,p2,p3])
g2 = GeoSeries([p2,p3])

g = GeoSeries([Polygon([(0,0), (0,2), (2,2), (2,0)])])

g1.intersects(g) # Flags the first point as inside, even though all are.
g2.intersects(g) # The second point gets picked up as inside (but not 3rd)
like image 236
Thomas Pingel Avatar asked May 22 '15 20:05

Thomas Pingel


People also ask

How do you find where two polygons intersect?

Compute the center of mass for each polygon. Compute the min or max or average distance from each point of the polygon to the center of mass. If C1C2 (where C1/2 is the center of the first/second polygon) >= D1 + D2 (where D1/2 is the distance you computed for first/second polygon) then the two polygons "intersect".

How do you check if a line intersects a polygon?

Draw a horizontal line to the right of each point and extend it to infinity. Count the number of times the line intersects with polygon edges. A point is inside the polygon if either count of intersections is odd or point lies on an edge of polygon.

How do you check if two polygons intersect in Python?

In Sympy, the function Polygon. intersection() is used to get the intersection of a given polygon and the given geometry entity. The geometry entity can be a point, line, polygon, or other geometric figures. The intersection may be empty if the polygon and the given geometry entity are not intersected anywhere.


2 Answers

Since geopandas underwent many performance-enhancing changes recently, answers here are outdated. Geopandas 0.8 introduced many changes that makes handling large datasets a lot faster.

import geopandas
from shapely.geometry import Polygon

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

points = GeoSeries([p1,p2,p3])

poly = GeoSeries([Polygon([(0,0), (0,2), (2,2), (2,0)])])

geopandas.overlay(points, poly, how='intersection')
like image 159
Magnus Avatar answered Sep 30 '22 14:09

Magnus


You can easily check which points lies inside a polygon with this simple function below:

import geopandas
from shapely.geometry import *

p1 = Point(.5,.5)
p2 = Point(.5,1)
p3 = Point(1,1)

g = Polygon([(0,0), (0,2), (2,2), (2,0)])

def point_inside_shape(point, shape):
    #point of type Point
    #shape of type Polygon
    pnt = geopandas.GeoDataFrame(geometry=[point], index=['A'])
    return(pnt.within(shape).iloc[0])

for p in [p1, p2, p3]:
    print(point_inside_shape(p, g))
like image 39
Ioannis Nasios Avatar answered Sep 30 '22 14:09

Ioannis Nasios