You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将路由字典中的索引替换为DataFrame中的坐标?

问题:用DataFrame坐标替换路由字典中的索引

我有如下结构的DataFrame:

name                         location   
0   Plaza Botero            ( -75.5686261812429,6.2524857541249315) 
1   Universidad de Medellín ( -75.6116092592174,6.231704691813073)
2   Parque Juanes de la Paz ( -75.56945687270888,6.290384323934336)
3   Parque del Poblado      ( -75.57088108434691,6.210362095508166) 
4   Alcaldía de Medellín    ( -75.57371337731854,6.2451496127526225)    
5   Parque Explora          ( -75.56556245591827,6.271208962002754) 

以及路由字典:

routes= {0: [0, 1, 0], 1: [0, 2, 3, 0], 2: [0, 5, 4, 0]}

需要创建一个新字典,用DataFrame中对应索引的location坐标替代原字典列表中的索引值。例如路由0的预期输出为:

route_0= {0:[( -75.5686261812429,6.2524857541249315),( -75.6116092592174,6.231704691813073),( -75.5686261812429,6.2524857541249315)]}

解决方案

步骤1:解析DataFrame中的坐标字符串

原DataFrame的location列是字符串格式,需要先转换成可直接使用的元组类型:

import pandas as pd

# 假设你的DataFrame已创建完成,名为df
df['location'] = df['location'].apply(
    lambda x: tuple(map(float, x.strip('()').split(',')))
)

步骤2:遍历路由字典替换索引

遍历routes字典的每个键值对,将列表中的每个索引替换为对应的坐标:

new_routes = {}
for route_id, index_list in routes.items():
    # 替换每个索引为对应的坐标
    coordinate_list = [df.loc[idx, 'location'] for idx in index_list]
    # 按照预期格式生成新字典
    new_routes[f'route_{route_id}'] = {route_id: coordinate_list}

最终效果

运行上述代码后,new_routes的内容会完全符合预期:

{
    'route_0': {0: [(-75.5686261812429, 6.2524857541249315), (-75.6116092592174, 6.231704691813073), (-75.5686261812429, 6.2524857541249315)]},
    'route_1': {1: [(-75.5686261812429, 6.2524857541249315), (-75.56945687270888, 6.290384323934336), (-75.57088108434691, 6.210362095508166), (-75.5686261812429, 6.2524857541249315)]},
    'route_2': {2: [(-75.5686261812429, 6.2524857541249315), (-75.56556245591827, 6.271208962002754), (-75.57371337731854, 6.2451496127526225), (-75.5686261812429, 6.2524857541249315)]}
}

如果不需要外层的route_数字键,直接保留原路由ID作为键,可修改代码为:

new_routes = {}
for route_id, index_list in routes.items():
    new_routes[route_id] = [df.loc[idx, 'location'] for idx in index_list]

得到的结果会是:

{
    0: [(-75.5686261812429, 6.2524857541249315), (-75.6116092592174, 6.231704691813073), (-75.5686261812429, 6.2524857541249315)],
    1: [(-75.5686261812429, 6.2524857541249315), (-75.56945687270888, 6.290384323934336), (-75.57088108434691, 6.210362095508166), (-75.5686261812429, 6.2524857541249315)],
    2: [(-75.5686261812429, 6.2524857541249315), (-75.56556245591827, 6.271208962002754), (-75.57371337731854, 6.2451496127526225), (-75.5686261812429, 6.2524857541249315)]
}

内容的提问来源于stack exchange,提问作者chilli93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:06:25