-2

I have two dataframe df1 and df2, I want to find out all the neighbouring points from df1 which is a neighbour to the points in df2(Need to find out for each point in the df2 in an iterative manner) within a particular radial distance.

How could I do that?

in the given figure: black points are in df1 and red points are in df2, I would like to find the neighbouring points of each red points . enter image description here

VGB
  • 447
  • 6
  • 21
  • 6
    Please provide a [mcve] – rafaelc Feb 11 '20 at 19:32
  • 1
    Welcome to StackOverflow. [On topic](https://stackoverflow.com/help/on-topic), [how to ask](https://stackoverflow.com/help/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is a knowledge base for *specific* programming problems -- not a design, coding, research, or tutorial resource. Post your code and the problem you're having. – Prune Feb 11 '20 at 19:55

2 Answers2

1

In pseudocode (not language specific and VERY loosely typed):



function getDistance(point pointA, point pointB){
  diffx = absoluteValue(pointA.x - pointB.x);
  diffy = absoluteValue(pointA.y - pointB.y);
  return squareRoot(diffx^2 + diffy^2)
}

for point1 in df1{

  //each obj stores a point and a corresponding distance
  Object distance{
    point2Identifier;
    distanceFromPoint1;
  }
  ObjectArray distances;  //Array of distance objects 

  for point2 in df2{
    distances.add(getDistance(point1, point2)); 
  }
  distances.getSmallest /*Finds the distance obj  with the smallest distanceFromPoint1 prop and stores it however you see fit*/
}

This was off the top of my head and quickly typed, so simplification and implementation are up to you. This most likely is not the quickest nor the most efficient way of achieving what you want. I am sure it can be simplified greatly, especially in Python. As you probably know, the API is littered with methods for simplifying math-in-code.

Nate T
  • 727
  • 5
  • 21
0

Find all nearest neighbors within a specific distance

#x,y are the x, y columns in the data frame and the radial distance is 0.1
import numpy as np
import scipy.spatial as spatial


points=df1[['x','y']]
points_array= points.rename_axis('ID').values


point_tree = spatial.cKDTree(points_array)


for item in range(0,len(df2),1):
 print(point_tree.data[point_tree.query_ball_point([df2.x.iloc[item], cells_final.lat.iloc[item]], 0.1)])

VGB
  • 447
  • 6
  • 21