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

遍历Pandas DataFrame字典提取所有工作表同一行数据的解决方案

问题根因

当pandas.read_excel()的sheet_name参数设置为None时,函数返回值不是单个DataFrame对象,而是键为工作表名称、值为对应工作表内容生成的DataFrame的字典结构,字典类型本身没有iloc属性,直接调用就会抛出AttributeError: 'dict' object has no attribute 'iloc'报错。

实现方案

方案1:逐表提取并打印指定行

适合只需要临时查看各表目标行数据的场景,直接遍历返回的字典即可:

import pandas as pd

# 读取所有工作表
all_sheet_dict = pd.read_excel(r'C:\Users\User\SomeFile.xlsx', sheet_name=None)
target_row_idx = 9  # 要提取的行索引,对应需求中要取的第9行

for sheet_name, df in all_sheet_dict.items():
    print(f"===== 工作表:{sheet_name} 第{target_row_idx}行数据 =====")
    print(df.iloc[target_row_idx])
    print("\n")

方案2:提取所有表的目标行并汇总为新DataFrame

适合需要把各表提取到的行整合起来做后续分析的场景,提取后可以合并成统一的结构化结果:

import pandas as pd

all_sheet_dict = pd.read_excel(r'C:\Users\User\SomeFile.xlsx', sheet_name=None)
target_row_idx = 9
row_list = []

for sheet_name, df in all_sheet_dict.items():
    # iloc传入[索引值]返回DataFrame格式,方便后续合并操作
    single_row = df.iloc[[target_row_idx]].copy()
    # 新增列标记数据来源工作表,方便后续溯源
    single_row["来源工作表"] = sheet_name
    row_list.append(single_row)

# 合并所有提取到的行,重置索引
final_result = pd.concat(row_list, ignore_index=True)
print(final_result)
异常兼容处理

如果存在部分工作表行数不足、不存在索引为9的行的情况,直接运行会抛出IndexError,可以在遍历逻辑里加长度判断跳过异常表:

for sheet_name, df in all_sheet_dict.items():
    # 行数小于等于目标索引值,说明不存在对应行
    if len(df) <= target_row_idx:
        print(f"工作表【{sheet_name}】行数不足,已跳过")
        continue
    # 此处编写正常提取、处理数据的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 06:45:41