# Subsetting a Pandas dataframe based on latitude and longitude values and coordinates of a circular boundary in Python

I have a dataset with coordinates (LAT and LON) and boundary coordinates of a circle (shown in the figure below). I want to subset a dataset based on coordinates of this circular boundary for getting the data only inside this boundary.

Dataset (df):

LAT LON Value
22.9000 -79.0000 ..
.. .. ..

Coordinates for Circular Boundary:

LAT LON
25.516838 -76.976036
.. ..

I tried as follows:

``````df_350km_radius = df[df['LAT'].between(min_lat_rad, max_lat_rad) & df['LON'].between(min_lon_rad, max_lon_rad)]
``````

But I am getting data outside of the circle. How can I get values only inside the circle using Python?

• Use a distance expression rather than the intersection of independent coordinates. Nov 8, 2021 at 23:35
• I calculated the distance from the center point and then selected all points which have a distance <= 350 KM. It solved my problem. Thanks.
– Javy
Nov 9, 2021 at 20:41

## 1 Answer

You can use the `shapely` and `geopandas` libraries to do that.

Here's how:

``````# Importing libraries
import numpy as np
import pandas as pd
import geopandas as gpd
import shapely

#######################################
### Setting up reproducible example ###
#######################################

# Establishing initial variables similar to the ones in the original question
num_pts = 1000

df_points = pd.DataFrame({'id':range(num_pts),
'lon':np.random.rand(num_pts),
'lat':np.random.rand(num_pts)})

circle_coords = np.array([(1.0, 0.5),
(0.75, 0.9330127018922193),
(0.2500000000000001, 0.9330127018922194),
(0.0, 0.5000000000000001),
(0.24999999999999978, 0.06698729810778076),
(0.75, 0.0669872981077807)])

df_circle = pd.DataFrame({'id':range(len(circle_coords)),
'lon':circle_coords[:,0],
'lat':circle_coords[:,1]})

#####################################
### Performing spatial operations ###
#####################################

# Creating a GeoDataFrame for the points to be queried
gdf_points = gpd.GeoDataFrame(df_points,
crs='epsg:4326',
geometry=gpd.points_from_xy(df_points['lon'],
df_points['lat']))

# Creating a GeoDataFrame for the points on the circle to use as a reference
gdf_circle = gpd.GeoDataFrame(df_circle,
crs='epsg:4326',
geometry=gpd.points_from_xy(df_circle['lon'],
df_circle['lat']))

# Generating a shapely geometry from the sequence of circle Points
circle_shape = shapely.geometry.Polygon(gdf_circle['geometry'])

# Querying which points are actually within the circle geometry
gdf_points['in_circle'] = gdf_points.intersects(circle_shape)
``````

In the example above, the `gdf_points['in_circle']` column will contain a bunch of `True` or `False` values indicating if the point is inside the circle or not, respectively.