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

如何根据索引提取DataFrame数据并合并排序生成目标列表?

问题

我有如下DataFrame:

idxval1val2
01512
11438
21188
39521
41998
51248
63538
72539
86528

已定义两个索引列表:

list1 = [0, 3, 6]
list2 = [5, 8]

需要实现:从list1的索引提取val1列数据,从list2的索引提取val2列数据,将所有提取的数据按原索引升序排列后组成目标列表,预期输出:

output = [15, 95, 48, 35, 28]
解决方案

分步实现代码

import pandas as pd

# 构建示例DataFrame
df = pd.DataFrame({
    'val1': [15,14,11,95,19,12,35,25,65],
    'val2': [12,38,88,21,98,48,38,39,28]
})

list1 = [0, 3, 6]
list2 = [5, 8]

# 收集(原索引, 对应值)的元组
data_with_index = []
for idx in list1:
    data_with_index.append((idx, df.loc[idx, 'val1']))
for idx in list2:
    data_with_index.append((idx, df.loc[idx, 'val2']))

# 按原索引排序后提取数值
output = [value for idx, value in sorted(data_with_index, key=lambda x: x[0])]

print(output)  # 输出: [15, 95, 48, 35, 28]

简化写法

用列表推导式合并收集步骤,代码更紧凑:

data_with_index = [(i, df.loc[i, 'val1']) for i in list1] + [(i, df.loc[i, 'val2']) for i in list2]
output = [v for _, v in sorted(data_with_index)]

原理说明

  • 核心思路是将每个提取的值和它的原索引绑定,避免排序时丢失对应关系
  • 通过sorted()按原索引升序排列所有数据对
  • 最后从排序后的元组中提取数值部分,得到目标列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:57:38