简体   繁体   中英

Python pandas merge centroid data back to dataframe

Hi I am trying to Find the center point of multiple co-ordinates and then join the resultant data back to the main data set, this is what I have so far

Sample data

coords1=pd.DataFrame({'pickup_latitude':[12.807895,12.82166,12.821675,12.82168,12.821697,12.8217,12.821718,12.821722,12.821751,12.821771,12.821782,12.821794,12.821828,12.821873,12.821892,12.821892,12.821929,12.821935,12.821947,12.821979],'pickup_longitude':[77.590877,77.658981,77.660594,77.660634,77.657854,77.657992,77.659848,77.660243,77.659244,77.658826,77.660763,77.660614,77.659569,77.660678,77.659861,77.660629,77.660488,77.660537,77.657746,77.66077]})

The code I have have so far

    import pandas as pd, numpy as np, matplotlib.pyplot as plt
    from sklearn.cluster import DBSCAN
    from geopy.distance import great_circle
    from shapely.geometry import MultiPoint
    
        
    ms_per_radian = 6371.0088
    epsilon = 0.00001 
    db = DBSCAN(eps=epsilon, min_samples=1, algorithm='ball_tree', metric='haversine').fit(np.radians(coords))
    cluster_labels = db.labels_
    num_clusters = len(set(cluster_labels))
    clusters = pd.Series([coords[cluster_labels == n] for n in range(num_clusters)])
    print('Number of clusters: {}'.format(num_clusters))
    
    
    def get_centermost_point(cluster):
        centroid = (MultiPoint(cluster).centroid.x, MultiPoint(cluster).centroid.y)
        centermost_point = min(cluster, key=lambda point: great_circle(point, centroid).m)
        return tuple(centermost_point)
    
    centermost_points = clusters.map(get_centermost_point)
    
    
    lats, lons = zip(*centermost_points)
    rep_points = pd.DataFrame({'lon':lons, 'lat':lats})
    
    rep_points.tail()
    
    
    rs = rep_points.apply(lambda row: Lat_Long_pick[(Lat_Long_pick['pickup_latitude']==row['lat'])&(Lat_Long_pick['pickup_longitude']==row['lon'])].iloc[0], axis=1)
                                                     

How do I now Join rs back to Lat_Long_pick or coords1

IF you facing problem merging then You can merge two dataframe like below or if issue if different please comment

left = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
                  'A': ['A0', 'A1', 'A2'],
                  'B': ['B0', 'B1', 'B2']})

right = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
                   'C': ['C0', 'C1', 'C2'],
                   'D': ['D0', 'D1', 'D2']})

df = pd.merge(left, right, on='key')
df

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM