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

如何从嵌套列表与DataFrame生成坐标DataFrame?求优化方案

问题背景

我有一个嵌套列表:

tours = [[0, 4], [0, 5], [0, 6], [1, 13], [2, 0], [3, 8], [4, 9], [5, 10],
[6, 7], [7, 1], [8, 2], [9, 3], [10, 11], [11, 14], [12, 0], [13, 12], [14, 0]]

同时拥有一个Pandas DataFrame df:

Node       X      Y  Demand  Profit
1      2  5.7735   0.00    40.0    16.0
2      3  2.8867   5.00    40.0    16.0
3      4 -2.8868   5.00    40.0    16.0
4      5 -5.7735   0.00    40.0    16.0
5      6 -2.8867  -5.00    40.0    16.0
6      7  2.8868  -5.00    40.0    16.0
7      8  8.6603   5.00    40.0    24.0
8      9  0.0000  10.00    40.0    24.0
9     10 -8.6603   5.00    40.0    24.0
10    11 -8.6603  -5.00    40.0    24.0
11    12  0.0000 -10.00    40.0    24.0
12    13  8.6603  -5.00    40.0    24.0
13    14  5.3405   0.75    10.0    10.0
14    15  3.3198   4.25    10.0    10.0
15    16  6.4952  -1.25    10.0    11.0

嵌套列表tours中每个子列表的第一个元素对应df中X列的索引,第二个元素对应Y列的索引,例如[0,4]对应X=5.7735,Y=-5.00。

需求目标

生成包含X、Y两列的新DataFrame coord,每行对应tours中一个元素定义的坐标对,最终用于绘制完整路线。

已尝试方案

我通过循环生成字典再转换为DataFrame的方法实现了需求,但希望找到更简便的优化方案:

d = {}
for t,tour in enumerate(tours):
    xi = tour[0]
    yi = tour[1]
    key = t
    d[key] = df["X"].iloc[xi], df["Y"].iloc[yi]
coord = pd.DataFrame.from_dict(d, orient='index', columns= ['X','Y'])

该方案输出结果符合预期,但有没有比“嵌套列表→字典→DataFrame”更简便的实现方式?


优化方案

方法1:列表推导式直接构造

最简洁的写法是用列表推导式生成坐标元组列表,直接传入pd.DataFrame,跳过字典转换的中间步骤:

coord = pd.DataFrame(
    [(df["X"].iloc[xi], df["Y"].iloc[yi]) for xi, yi in tours],
    columns=["X", "Y"]
)

方法2:向量化批量索引(高性能)

如果tours数据量较大,推荐使用向量化操作,利用Pandas的批量索引优化,避免Python循环的开销:

# 拆分出所有X和Y的索引
x_idx, y_idx = zip(*tours)
# 批量提取值并构造DataFrame
coord = pd.DataFrame({
    "X": df["X"].iloc[list(x_idx)],
    "Y": df["Y"].iloc[list(y_idx)]
}).reset_index(drop=True)

这两种方法都比原方案更精简,性能也更优:列表推导式省去了字典键值对的构建过程,向量化操作则充分利用Pandas的底层效率,数据量越大优势越明显。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:42:03