首页 > 解决方案 > 从列表创建字典项目列表

问题描述

我正在开展一个项目,该项目涉及通过两列纬度和经度值。如果一对列中的纬度/经度是空白的,那么我需要找出另外两列中的哪对纬度/经度值(在地理上)最接近目的地中的纬度/经度值。数据框如下所示:

 origin_lat  |   origin_lon  |  destination_lat  |  destination_lon
----------------------------------------------------------------
 20.291326      -155.838488       25.145242          -98.491404
 25.611236      -80.551706        25.646763          -81.466360
 26.897654      -75.867564          nan                 nan

我正在尝试构建两个字典,一个带有原始纬度和经度,另一个带有目的地纬度和经度,格式如下:

tmplist = [{'origin_lat': 39.7612992, 'origin_lon': -86.1519681}, 
           {'origin_lat': 39.762241,  'origin_lon': -86.158436 }, 
           {'origin_lat': 39.7622292, 'origin_lon': -86.1578917}]

我想要做的是对于目的地纬度/经度为空白的每一行,将同一行中的原始纬度/经度与所有非南目的地纬度/经度值的字典进行比较,然后打印地理上最接近的纬度/ lon 从目标纬度/经度字典到代替 nan 值的行。我一直在尝试创建字典对象列表,但似乎无法以正确的格式构建字典。任何帮助,将不胜感激!

标签: python

解决方案


如果df是您的pandas.DataFrame,您可以通过遍历以下行来生成请求的字典df

origin_dicts = [{'origin_lat': row['origin_lat'], 'origin_long': row['origin_lon']} for _, row in df.iterrows()]

和类似地对于destination_dicts

备注:如果创建字典的唯一原因是计算替换 - 条目的值nan,则直接在数据框上执行此操作可能更容易,例如

df['destination_lon'] = df.apply(find_closest_lon, axis=1)
df['destination_lat'] = df.apply(find_closest_lat, axis=1)

其中find_closest_lon,find_closes_lat是接收数据帧行作为参数的函数,并且可以访问数据帧的原始列的值。


推荐阅读