如何创建以city1为索引、city2为列的累积距离透视表并设对角线为0?
解决方案
你的原始数据是城市间的相邻距离链,直接用cumsum()和pivot()无法生成完整的累积距离矩阵——pivot()只会填充现有(city1,city2)对的值,其余位置为NaN,且全局cumsum()不是按起点分组的累积。以下是可行的解决步骤:
步骤1:加载原始数据
先把数据集用pandas初始化:
import pandas as pd import numpy as np # 原始数据集 df3 = pd.DataFrame({ 'city1': [101, 102, 103, 104], 'city2': [102, 103, 104, 105], 'distance': [56, 34, 6, 15] })
步骤2:生成完整城市列表并初始化零矩阵
提取所有涉及的城市,创建一个对角线为0的空矩阵:
# 获取所有城市并排序 cities = sorted(set(df3['city1'].tolist() + df3['city2'].tolist())) # 初始化全零透视表,索引和列均为城市 pivot_df = pd.DataFrame(0, index=cities, columns=cities)
步骤3:计算并填充累积距离
先计算全局累积距离数组,再根据城市位置映射填充矩阵:
# 生成包含起点0的累积距离数组(对应101→101:0, 101→102:56, 101→103:90...) cumulative_distances = np.cumsum([0] + df3['distance'].tolist()) # 创建城市到数组索引的映射 city_to_idx = {city: idx for idx, city in enumerate(cities)} # 填充上三角区域的累积距离 for start_city in cities: start_idx = city_to_idx[start_city] for end_city in cities[start_idx+1:]: end_idx = city_to_idx[end_city] pivot_df.loc[start_city, end_city] = cumulative_distances[end_idx] - cumulative_distances[start_idx]
最终结果
运行后得到的pivot_df就是符合要求的透视表:
| 101 | 102 | 103 | 104 | 105 | |
|---|---|---|---|---|---|
| 101 | 0 | 56 | 90 | 96 | 111 |
| 102 | 0 | 0 | 34 | 40 | 55 |
| 103 | 0 | 0 | 0 | 6 | 21 |
| 104 | 0 | 0 | 0 | 0 | 15 |
| 105 | 0 | 0 | 0 | 0 | 0 |
如果需要双向距离(比如102→101也显示56),可以在循环中添加pivot_df.loc[end_city, start_city] = cumulative_distances[end_idx] - cumulative_distances[start_idx]。
内容的提问来源于stack exchange,提问作者Kishore Kumar
相关产品推荐
相关产品推荐

