【问题标题】:Create list of dictionary items from lists从列表创建字典项目列表
【发布时间】:2021-03-09 23:27:07
【问题描述】:

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

 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

我正在尝试构建两个字典,一个带有原始 lat 和 long,另一个带有目标 lat 和 long,格式如下:

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    您想要的格式是内置的“记录”格式:

    df[['origin_lat','origin_lon']].to_dict(orient = 'records')
    

    生产

    [{'origin_lat': 20.291326, 'origin_lon': -155.83848799999998},
     {'origin_lat': 25.611235999999998, 'origin_lon': -80.55170600000001},
     {'origin_lat': 26.897654, 'origin_lon': -75.867564}]
    

    当然你也可以拥有

    df[['destination_lat','destination_lon']].to_dict(orient = 'records')
    

    但我同意 @ctenar 的观点,即您不需要为最终任务生成字典,Pandas 提供了足够的功能

    【讨论】:

      【解决方案2】:

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

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

      同样适用于destination_dicts

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

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

      其中find_closest_lonfind_closes_lat 是接收数据框行作为参数并可以访问数据框原始列的值的函数。

      【讨论】:

      • 直接在数据框上执行此操作对我有用,因为我已经拥有查找最接近的经纬度的功能。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多