如何使用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 → Manchester | 1 | 2 |
| Manchester → Oxford | 2 | 3 |
| Oxford → London | 1 | 4 |
逻辑说明
- 以
City of origin(出发城市)和Destination city(目的城市)两个字段作为分组键,相同组合的行会被归为同一组 agg方法针对每组的市区、郊野通行时间列分别计算最小值,得到对应路线的最短通行时间as_index=False参数用于避免分组键转为行索引,方便后续数据处理
内容的提问来源于stack exchange,提问作者João Galdino
相关产品推荐
相关产品推荐

