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

如何使用Pandas按路线分组获取各路线市区、郊野的最小通行时间

实现方法

你可以直接使用Pandas的groupby分组聚合功能实现需求,具体处理代码如下:

import pandas as pd

# 示例数据构造
dict_ = {'City of origin':["Oxford","Oxford","Oxford","London","London","London","Manchester","Manchester","Manchester"],
     'Destination city':["London","London","London","Manchester","Manchester","Manchester","Oxford","Oxford","Oxford"],
     'Downtown':[2,1,6,1,4,5,2,8,4],
     'Countryside':[4,8,7,2,8,8,3,10,15]
    }
df = pd.DataFrame(dict_)

# 按出发城市、目的城市分组,聚合求两类通行时间的最小值
result = df.groupby(
    ['City of origin', 'Destination city'], 
    as_index=False
).agg(
    最短市区通行时间=('Downtown', 'min'),
    最短郊野通行时间=('Countryside', 'min')
)

# 可选:合并出发、目的城市为单一路线列,输出格式更直观
result['路线'] = result['City of origin'] + ' → ' + result['Destination city']
result = result.reindex(columns=['路线', '最短市区通行时间', '最短郊野通行时间'])

print(result)

输出结果

运行上述代码后得到的聚合结果如下:

路线最短市区通行时间最短郊野通行时间
London → Manchester12
Manchester → Oxford23
Oxford → London14

逻辑说明

  • 以City of origin(出发城市)和Destination city(目的城市)两个字段作为分组键,相同组合的行会被归为同一组
  • agg方法针对每组的市区、郊野通行时间列分别计算最小值,得到对应路线的最短通行时间
  • as_index=False参数用于避免分组键转为行索引,方便后续数据处理

内容的提问来源于stack exchange,提问作者João Galdino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:09:02