Home > Enterprise >  filter a dataframe with rows inside a polygon
filter a dataframe with rows inside a polygon

Time:01-05

I have a dataframe with columns of x, y, data. and I have a list for polygon coordinate like this: polygon=[x1,y1,x2,y2,x3,y3,x4,y4]

I'd like to filter out all the rows of dataframe with (x,y) outside the polygon


df.columns=['x','y','data']
polygon=[x1,y1,x2,y2,x3,y3,x4,y4]

df_1= df inside polygon

How to implement the last line? Thanks

CodePudding user response:

See Shapely:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

df['point'] = df.apply(lambda row: Point(row['x'],row['y']),axis=1)
polygon = Polygon([(x1,y1), (x2,y2), (x3,y3), (x4,y4)])
df_1 = df[df['point'].apply(polygon.contains)].copy()
  •  Tags:  
  • Related