closest point python

Solutions on MaxInterview for closest point python by the best coders in the world

showing results for - "closest point python"
Edoardo
21 Jun 2017
1#kd-tree for quick nearest-neighbor lookup
2import geopandas as gpd
3import numpy as np
4import pandas as pd
5
6from scipy.spatial import cKDTree
7from shapely.geometry import Point
8
9gpd1 = gpd.GeoDataFrame([['John', 1, Point(1, 1)], ['Smith', 1, Point(2, 2)],
10                         ['Soap', 1, Point(0, 2)]],
11                        columns=['Name', 'ID', 'geometry'])
12gpd2 = gpd.GeoDataFrame([['Work', Point(0, 1.1)], ['Shops', Point(2.5, 2)],
13                         ['Home', Point(1, 1.1)]],
14                        columns=['Place', 'geometry'])
15
16def ckdnearest(gdA, gdB):
17    nA = np.array(list(gdA.geometry.apply(lambda x: (x.x, x.y))))
18    nB = np.array(list(gdB.geometry.apply(lambda x: (x.x, x.y))))
19    btree = cKDTree(nB)
20    dist, idx = btree.query(nA, k=1)
21    gdf = pd.concat(
22        [gdA.reset_index(drop=True), gdB.loc[idx, gdB.columns != 'geometry'].reset_index(drop=True),
23         pd.Series(dist, name='dist')], axis=1)
24    return gdf
25
26ckdnearest(gpd1, gpd2)