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

使用Python合并多份Excel文件时丢失列及索引异常问题

问题解决思路与修正代码

1. "Total Received"列及衍生列缺失的问题

  • 核心原因:pd.read_excel()的usecols="A:D,R"参数仅读取了A-D列和R列,若"Total Received"列不在指定范围内,程序就无法读取到该列数据,后续依赖它的衍生列自然也会缺失。
  • 修正方案:
    • 若明确知道"Total Received"列的位置,将其加入usecols参数(比如该列是E列,就改成usecols="A:E,R");
    • 不确定列位置时,直接移除usecols参数,读取文件所有列;
    • 代码中df['Total Received']是无效语句,仅列访问操作未做任何实际处理,直接删除即可。

2. A列索引无法移除的问题

  • 问题本质:保存Excel时,to_excel()默认会把DataFrame的索引写入为单独一列。解决方法是在to_excel()中添加index=False参数,禁止写入索引列。
  • 额外优化:不要在循环内重复执行finalDf.to_excel(),应在所有文件合并完成后统一保存,避免资源浪费。

修正后的完整代码

import pandas as pd
import os

path = "C:\\Users\\Adam\\Desktop\\Stock Trackers\\New Folder\\"
finalDf = pd.DataFrame()

# 先获取文件夹内的所有Excel文件名(需确保导入os模块)
filenames = [f for f in os.listdir(path) if f.endswith('.xlsx')]

for file in filenames:
    if file.startswith("Stock"): 
        # 移除usecols参数以读取所有列,或按需调整列范围
        df = pd.read_excel(path + file, index_col=None) 
        df['Qty Received'] = df['Total Received']
        df['InvoicedValue'] = df['Price'] * df['Qty Invoiced']
        df['ReceivedValue'] = df['Price'] * df['Qty Received']
        df['DeltaQty'] = df['Qty Received'] - df['Qty Invoiced']
        df['DeltaValue'] = df['ReceivedValue'] - df['InvoicedValue']
        finalDf = pd.concat([finalDf, df])

# 添加index=False参数,避免写入索引列
finalDf.to_excel("finalfile12.xlsx", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:41