python - 从列表创建字典项目列表
问题描述
我正在开展一个项目,该项目涉及通过两列纬度和经度值。如果一对列中的纬度/经度是空白的,那么我需要找出另外两列中的哪对纬度/经度值(在地理上)最接近目的地中的纬度/经度值。数据框如下所示:
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 值的行。我一直在尝试创建字典对象列表,但似乎无法以正确的格式构建字典。任何帮助,将不胜感激!
解决方案
如果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
是接收数据帧行作为参数的函数,并且可以访问数据帧的原始列的值。
推荐阅读
- ag-grid-angular - 使用社区版本导入 AgGridModule 时出现问题
- javascript - 如何使用 cleanSession 标志,或使用 aws mqtt JS sdk 保留标志?
- bash - system() 失败,而命令在终端中运行良好
- r - 根据条件进行条件汇总并每月重复组,使用 dplyr 更改日期间隔范围
- python - 将 Flask + Vue 应用程序部署到 heroku 时出错
- php - Laravel Pusher Websocket 在 HTTPS 上不工作
- python - 带有python的octave cov函数(numpy?)
- python - PowerShell:无法解码 JSON 对象:期望用双引号括起来的属性名称
- pandas - 与从 rpy2 获取 `POSIXct` 的 R 函数不一致
- headless - Headless Chrome - 共享凭证