【问题标题】:Python pandas merge centroid data back to dataframePython pandas 将质心数据合并回数据框
【发布时间】:2019-08-09 13:32:28
【问题描述】:

您好,我正在尝试查找多个坐标的中心点,然后将结果数据连接回主数据集,这是我目前所拥有的

样本数据

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]})

我目前拥有的代码

    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)
                                                     

我现在如何加入 rs 回到 Lat_Long_pick 或 coords1

【问题讨论】:

    标签: python pandas geopandas sklearn-pandas geo


    【解决方案1】:

    如果您遇到合并问题,那么您可以合并两个数据框,如下所示,或者如果问题不同,请发表评论

    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
    

    【讨论】:

    • 初始数据帧 coords1 或 Lat_Long_pick 具有pickup_latitude 和pickup_longitude 数据,而生成的数据帧 rs 仅具有最中心的纬度和经度数据。不知道如何为两个数据框创建一个公共索引来合并它们
    • 请用一些虚拟数据发布两个数据帧(coords1,rs)
    • 当您运行代码时,我已经用一些虚拟数据更新了问题,它会为您提供 3 个结果pickup_latitudepickup_longitude 12.807895 77.590877 12.821722 77.660243 12.821697 77.657854 所以这 3 个结果坐标应该在 20 个主坐标中重复
    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2021-12-14
    • 2017-07-10
    • 1970-01-01
    • 2018-05-01
    • 2015-11-25
    相关资源
    最近更新 更多