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

Python Pandas:基于DataFrame按规则生成多个Excel文件

问题描述

现有如下Pandas DataFrame数据:

Invoice No.Voucher IDClaimed
MHI000000038710100039Yes
MHI000000038715100039No
MHI000000038711100043Yes
MHI000000038712100043No

需求:

  • 仅针对Claimed字段为Yes的Invoice No.生成对应的Excel文件
  • 每个Excel文件需包含该Invoice No.所属Voucher ID的全部行(无论Claimed是Yes或No)

示例输出:

  • 生成MHI000000038710.xlsx,包含Voucher ID为100039的所有行
  • 生成MHI000000038711.xlsx,包含Voucher ID为100043的所有行

当前脚本会为所有Invoice生成文件,无法满足需求:

for myid in df['Voucher ID'].unique():
    df_singleID = df[df['Voucher ID']==myid]
    for myinvoice in df_singleID['Invoice No'].unique():
        df_singleID.to_excel(output+"\\"+str(myinvoice)+'.xlsx',index = False)
解决方案

核心思路:先筛选出Claimed为Yes的记录,提取对应的Invoice No.和Voucher ID,再针对每个符合条件的Invoice No.,导出其所属Voucher ID的全部数据。

修正后的代码:

# 筛选Claimed为Yes的记录,提取关键字段
claimed_records = df[df['Claimed'] == 'Yes'][['Invoice No.', 'Voucher ID']]

# 遍历每个符合条件的发票记录
for _, row in claimed_records.iterrows():
    invoice_name = row['Invoice No.']
    target_voucher = row['Voucher ID']
    # 获取该凭证ID对应的所有行数据
    voucher_data = df[df['Voucher ID'] == target_voucher]
    # 导出Excel文件
    voucher_data.to_excel(f"{output}\\{invoice_name}.xlsx", index=False)

代码说明

  1. 精准筛选目标:claimed_records只保留需要生成文件的发票记录,避免无效遍历;
  2. 定向导出数据:对每个目标发票,找到其所属的凭证ID,提取该凭证下的所有行,再以发票号为文件名导出,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:01:01