title: K-nearest points from two dataframes with GeoPandas
body: <p>GeoPandas uses shapely under the hood. To get the nearest neighbor I saw the use of <code>nearest_points</code> <a href="https://gis.stackexchange.com/questions/222315/geopandas-find-nearest-point-in-other-dataframe">from shapely</a>. However, this approach does not include k-nearest points. </p>
  
  <p>I needed to compute distances to nearest points from to GeoDataFrames and insert the distance into the GeoDataFrame containing the "from this point" data.</p>
  
  <p>This is my approach using <code>GeoSeries.distance()</code> without using another package or library. Note that when <code>k == 1</code> the returned value essentially shows the distance to the nearest point. <a href="https://stackoverflow.com/questions/30740046/calculate-distance-to-nearest-feature-with-geopandas">There is also a GeoPandas-only solution for nearest point by @cd98 which inspired my approach</a>.</p>
  
  <p>This works well for my data, but I wonder if there is a better or faster approach or another benefit to use shapely or <a href="https://stackoverflow.com/questions/12369484/searching-for-k-nearest-points">sklearn.neighbors</a>?</p>
  
  <pre><code>import pandas as pd
  import geopandas as gp
  
  gdf1 &gt; GeoDataFrame with point type geometry column - distance from this point
  gdf2 &gt; GeoDataFrame with point type geometry column - distance to this point
  
  def knearest(from_points, to_points, k):
      distlist = to_points.distance(from_points)
      distlist.sort_values(ascending=True, inplace=True) # To have the closest ones first
      return distlist[:k].mean()
  
  # looping through a list of nearest points
  for Ks in [1, 2, 3, 4, 5, 10]:
      name = 'dist_to_closest_' + str(Ks) # to set column name
      gdf1[name] = gdf1.geometry.apply(knearest, args=(gdf2, closest_x))
  </code></pre>