Finding points in radius of each point in same GeoDataFrame

120

Question: Finding points in radius of each point in same GeoDataFrame

I have geoDataFrame:

df = gpd.GeoDataFrame([[0, 'A', Point(10,12)],                         [1, 'B', Point(14,8)],                        [2, 'C', Point(100,2)],                        [3, 'D' ,Point(20,10)]],                        columns=['ID','Value','geometry']) 

Is it possible to find points in a range of radius for example 10 for each point python-3.x error and add their "Value" and 'geometry' to GeoDataFrame so output would look like:

['ID','Value','geometry','value_of_point_in_range_1','geometry_of_point_in_range_1','value_of_point_in_range_2','geometry_of_point_in_range_2' etc.] 

Before i was finding nearest neighbor for each and after that was checking if python-3.x error is it in range but i must find all of the points in radius and don't know what tool should i use.

Total Answers: 1

9

Answers 1: of Finding points in radius of each point in same GeoDataFrame

Although in your example the output will have a predictable amount of columns in the resulting dataframe, this not true in general. Therefore I would instead create a column in the dataframe that consists of python-3.x error a lists denoting the index/value/geometry of the nearby points.

In a small dataset like you provided, simple arithmetics in python python-3.x error will suffice. But for large datasets you will want to use a spatial tree to query the nearby points. I suggest to use scipy's KDTree like this:

import geopandas as gpd import numpy as np from shapely.geometry import Point from scipy.spatial import KDTree  df = gpd.GeoDataFrame([[0, 'A', Point(10,12)],                        [1, 'B', Point(14,8)],                        [2, 'C', Point(100,2)],                        [3, 'D' ,Point(20,10)]],                       columns=['ID','Value','geometry'])  tree = KDTree(list(zip(df.geometry.x, df.geometry.y))) pairs = tree.query_pairs(10)  df['ValueOfNearbyPoints'] = np.empty((len(df), 0)).tolist()  n = df.columns.get_loc("ValueOfNearbyPoints") m = df.columns.get_loc("Value") for (i, j) in pairs:     df.iloc[i, n].append(df.iloc[j, m])     df.iloc[j, n].append(df.iloc[i, m]) 

This yields the following dataframe:

   ID Value                   geometry ValueOfNearbyPoints 0   0     A  POINT (10.00000 12.00000)                 [B] 1   1     B   POINT (14.00000 8.00000)              [A, D] 2   2     C  POINT (100.00000 2.00000)                  [] 3   3     D  POINT (20.00000 10.00000)                 [B] 

To verify the results, you may find plotting the result usefull:

import matplotlib.pyplot as plt ax = plt.subplot() df.plot(ax=ax) for (i, j) in pairs:     plt.plot([df.iloc[i].geometry.x, df.iloc[j].geometry.x],              [df.iloc[i].geometry.y, df.iloc[j].geometry.y], "-r") plt.show() 

enter image description here