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

代码单独运行正常,封装为函数循环调用后返回空DataFrame

问题诊断与解决方案

核心问题1:初始化空DataFrame的拼写错误

你代码里的output = pd.Dataframe()是拼写错误,正确写法应为pd.DataFrame()(注意Frame首字母为大写F)。这个错误会导致output并非有效空DataFrame,后续pd.concat无法正常拼接数据,最终返回空结果。

核心问题2:全局变量的不合理使用

虽然你用了global声明,但全局变量在循环调用中易引发不可预期的问题,且不利于代码维护。更合理的做法是让函数返回处理后的tmp_df,在循环外部统一完成拼接操作。

修正后的代码示例

import pandas as pd

def get_help(sheet, head, file):
    # 读取Cover工作表提取元数据
    tmp_df = pd.read_excel(file, sheet_name='Cover')
    tmp_df = tmp_df.dropna(how='all')
    tmp_df = tmp_df.dropna(axis=1, how='all')
    fnf = tmp_df.iloc[3, 0] 
    # 若currency、q_date后续未使用可删除,按需保留即可
    # currency = tmp_df.iloc[5, 0]
    # q_date = tmp_df.iloc[7, 0]
    
    # 读取目标工作表并处理数据
    tmp_df = pd.read_excel(file, sheet_name=sheet, header=head)
    tmp_df = tmp_df.loc[tmp_df['banana'] != '--- End of Sheet ---']
    tmp_df['banana'] = tmp_df['banana'].astype(str).str.replace('hi', '')
    tmp_df['FNF'] = fnf
    tmp_df['banana'] = tmp_df['FNF'] + ' ' + tmp_df['banana']
    
    # 返回处理后的DataFrame,而非修改全局变量
    return tmp_df

# 循环调用示例
output = pd.DataFrame()  # 修正拼写错误
files = [...]  # 替换为你的文件列表
sheets = [...]  # 替换为对应工作表名称列表
heads = [...]  # 替换为对应表头行参数列表

for sheet, head, file in zip(sheets, heads, files):
    df = get_help(sheet, head, file)
    output = pd.concat([output, df], ignore_index=True)  # ignore_index避免索引重复

# 查看最终结果
print(output)

额外排查方向

  • 确认循环传入的sheet、head、file参数有效:比如工作表名称存在、表头参数与Excel文件实际表头位置匹配。
  • 若拼接后仍为空,单独调用get_help检查返回的df是否为空,排查是否是Excel读取逻辑或过滤条件(如tmp_df['banana'] != '--- End of Sheet ---')过滤掉了所有数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:05:43