Why is this not returning a count of number of points in each neighbourhoods (bounding box)?
import geopandas as gpd
def radius(points_neighbour, points_center, new_field_name, r):
"""
:param points_neighbour:
:param points_center:
:param new_field_name: new field_name attached to points_center
:param r: radius around points_center
:return:
"""
sindex = points_neighbour.sindex
pts_in_neighbour = []
for i, pt_center in points_center.iterrows():
nearest_index = list(sindex.intersection((pt_center.LATITUDE-r, pt_center.LONGITUDE-r, pt_center.LATITUDE+r, pt_center.LONGITUDE+r)))
pts_in_this_neighbour = points_neighbour[nearest_index]
pts_in_neighbour.append(len(pts_in_this_neighbour))
points_center[new_field_name] = gpd.GeoSeries(pts_in_neighbour)
Every loop gives the same result.
Second question, how can I find k-th nearest neighbour?
More information about the problem itself:
We are doing it at a very small scale e.g. Washington State, US or British Columbia, Canada
We hope to utilize geopandas as much as possible since it's similar to pandas and supports spatial indexing: RTree
For example, sindex here has method nearest, intersection, etc.
Please comment if you need more information. This is the code in class GeoPandasBase
@property
def sindex(self):
if not self._sindex_generated:
self._generate_sindex()
return self._sindex
I tried Richard's example but it didn't work
def radius(points_neighbour, points_center, new_field_name, r):
"""
:param points_neighbour:
:param points_center:
:param new_field_name: new field_name attached to points_center
:param r: radius around points_center
:return:
"""
sindex = points_neighbour.sindex
pts_in_neighbour = []
for i, pt_center in points_center.iterrows():
pts_in_this_neighbour = 0
for n in sindex.intersection(((pt_center.LATITUDE-r, pt_center.LONGITUDE-r, pt_center.LATITUDE+r, pt_center.LONGITUDE+r))):
dist = pt_center.distance(points_neighbour['geometry'][n])
if dist < radius:
pts_in_this_neighbour = pts_in_this_neighbour + 1
pts_in_neighbour.append(pts_in_this_neighbour)
points_center[new_field_name] = gpd.GeoSeries(pts_in_neighbour)
To download the shape file, goto https://catalogue.data.gov.bc.ca/dataset/hellobc-activities-and-attractions-listing and choose ArcView to download