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

Pandas DataFrame多索引批量读取迭代问题求助

问题

从xlsx文件读取数据,第一行是索引表头,第一列包含索引的接收日期和类型。已实现单个索引的Pandas DataFrame读取,但无法完成所有索引的批量读取,尝试循环或列表推导式未成功。当前代码只能处理单个索引,无法正确迭代f'{index_names[1]}_{val}'适配所有索引,也不知道如何修改sheet['C' + str(item)]实现多索引遍历,现有代码如下:

characteristic = [100, 200, 300, 400, 500, 600, 700]
index_names = [sheet[1][row].value for row in range(1,sheet.max_row) if sheet[1][row].value != None]

index_list = [pd.DataFrame(
{f'{index_names[1]}_{val}': [sheet['C' + str(item)].value for item in range(1,26) 
            if sheet['A' + str(item)].value == val] 
        for val in characteristic},
    index = ['April 12', 'April 20', 'April 29']
) for _ in range(39)]

代码较为繁琐,希望简化。补充:执行index_list[0].to_dict('tight')后得到结果如下:

{'index': ['April 12', 'April 20', 'April 29'],
 'columns': ['Second_index_100',
  'Second_index_200',
  'Second_index_300',
  'Second_index_400',
  'Second_index_500',
  'Second_index_600',
  'Second_index_700'],
 'data': [[0.43927605317127927,
   -0.24029588928209195,
   0.26450969805682434,
   0.18810770500537646,
   0.26586690176009525,
   0.21631310872586834,
   0.32927840726651636],
  [0.16442875037513777,
   0.12442062805633937,
   0.06353459713174614,
   0.14329091121735923,
   0.17469551024592245,
   0.20938555077590043,
   0.17154589574351475],
  [0.4615041268976439,
   0.6488484892496023,
   0.28007883537118355,
   0.5962923255606478,
   0.5924116517116391,
   0.559117121673802,
   0.6458160644845848]],
 'index_names': [None],
 'column_names': [None]}
解决方案

核心问题是你固定了index_names[1]和C列,没有遍历所有索引对应的列。假设每个索引对应一列(如第一个索引对应C列,第二个对应D列,以此类推),可按以下方式修改:

简化后的代码

import pandas as pd

characteristic = [100, 200, 300, 400, 500, 600, 700]
# 获取所有非空索引名称
index_names = [sheet[1][row].value for row in range(1, sheet.max_row) if sheet[1][row].value is not None]
# 固定日期索引
date_index = ['April 12', 'April 20', 'April 29']
# 数据列从C开始(对应数字编号3)
start_col_num = 3
index_list = []

# 遍历每个索引名称,生成对应DataFrame
for idx, name in enumerate(index_names):
    # 计算当前索引对应的列字母(C、D、E...)
    current_col = chr(ord('A') + start_col_num + idx - 1)
    df_data = {}
    for val in characteristic:
        # 筛选A列等于val的行,提取当前列的值
        values = [sheet[f'{current_col}{item}'].value 
                  for item in range(1, 26) 
                  if sheet[f'A{item}'].value == val]
        df_data[f'{name}_{val}'] = values
    # 生成DataFrame并加入列表
    index_list.append(pd.DataFrame(df_data, index=date_index))

代码说明

  • 用enumerate遍历index_names,同时获取索引位置,动态计算对应的数据列(从C开始依次往后)
  • 每个索引名称对应一列数据,自动生成{name}_{val}格式的列名
  • 拆分嵌套逻辑,代码结构更清晰,避免原列表推导式的繁琐

验证

执行index_list[0].to_dict('tight')会得到和之前一致的结果,index_list[1]及后续元素则对应其他索引的DataFrame,实现批量读取需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:33:22