2

I have a dataframe that contains X & Y co-ordinates. Some of these coordinates are outside my country of interest, India. I'm looking for a way to filter out all the coordinates outside the shapefile of India. Is there anyway to achieve this?

Here's the code I tried:

import pandas as pd
import shapefile
from shapely.geometry import Point 
from shapely.geometry import shape 

shp = shapefile.Reader("D:\Work\MOSDAC\ind.shp","r")
all_shapes = shp.shapes() 
all_records = shp.records()    

def InCountry(lo,la):
    point_to_check = (lo, la) 
    for i in range(len(all_shapes)):
        boundary = all_shapes[i] 
        if Point(point_to_check).within(shape(boundary)):
            #Inside country shape file
            return (1)
        else:
            #Outside country shape file
            #return (0) this doesn't work use pass instead   
            pass




final['X2'].apply(lambda x: float(x))

final['Y2'].apply(lambda x: float(x))

#Create copy of dataframe with only incountry coordinates
df_copy = final.apply(InCountry(final['X2'].tolist(),final['Y2'].tolist()))

1 Answer 1

2

It is possible to filter the shapefile using GeoPandas's within method of the GeoSeries class:

from os.path import normpath
from geopandas import read_file

path_to_points = normpath("C:/Users/taras/Python Scripts/geopandas/points.shp")
path_to_polygons = normpath("C:/Users/taras/Python Scripts/geopandas/union.shp")

points, polygons = read_file(path_to_points), read_file(path_to_polygons)

points_mask = points.within(polygons.loc[0, 'geometry'])

points_filtered = points.loc[points_mask]

References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.