【问题标题】:Pandas - Compare 2 dataframes and find nearest valuesPandas - 比较 2 个数据框并找到最接近的值
【发布时间】:2020-09-16 20:36:10
【问题描述】:

我在 Pandas 中有 2 个数据框,其中包含 longitudelatitude。我正在尝试遍历第一行中的每一行,并在第二个数据框中找到最匹配的 longitudelatitude

到目前为止,我在 python 中有这个,我在另一个 SO 帖子中找到了它......

from math import cos, asin, sqrt

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    return 12742 * asin(sqrt(a))

def closest(data, v):
    return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))

tempDataList = [{'lat': 39.7612992, 'lon': -86.1519681}, 
                {'lat': 39.762241,  'lon': -86.158436 }, 
                {'lat': 39.7622292, 'lon': -86.1578917}]

v = {'lat': 39.7622290, 'lon': -86.1519750}
print(closest(tempDataList, v))

我将尝试修改它以用于我的 pandas 数据帧,但有没有更有效的方法可以使用 PyProj 来做到这一点?

有人有例子或类似的代码吗?

【问题讨论】:

    标签: python pandas gis pyproj


    【解决方案1】:

    如果您使用 GIS 库,我认为您将能够更轻松地做到这一点。所以,如果你使用 geopandas 和 shapely,它会更舒服。 (也用到了pyproj。)从下面的代码开始。

    import pandas as pd
    import geopandas as gpd
    from shapely.ops import Point, nearest_points
    
    tempDataList = [{'lat': 39.7612992, 'lon': -86.1519681}, 
                    {'lat': 39.762241,  'lon': -86.158436 }, 
                    {'lat': 39.7622292, 'lon': -86.1578917}]
    
    df = pd.DataFrame(tempDataList)
    
    #make point geometry for geopandas
    geometry = [Point(xy) for xy in zip(df['lon'], df['lat'])]
    
    #use a coordinate system that matches your coordinates. EPSG 4326 is WGS84
    gdf = gpd.GeoDataFrame(df, crs = "EPSG:4326", geometry = geometry) 
    
    #change point geometry
    v = {'lat': 39.7622290, 'lon': -86.1519750}
    tp = Point(v['lon'], v['lat'])
    
    #now you can calculate the distance between v and others.
    gdf.distance(tp)
    
    #If you want to get nearest points
    multipoints = gdf['geometry'].unary_union
    queried_point, nearest_point = nearest_points(tp, multipoints)
    print(nearest_point)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2017-04-18
      • 1970-01-01
      • 2020-02-10
      • 2016-10-15
      相关资源
      最近更新 更多