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

Python用pandas append Excel数据仅生成单行,如何输出3行?

你现有代码的逻辑是3次独立遍历所有Excel文件,每次读取的1行数据都会纵向追加到结果表中,如果你有N个待读取的Excel文件,最终会生成3*N行的长表。如果要实现仅3行的输出,需要把同一个header位置的所有文件读取结果横向拼接,每个header位置对应1行结果。

调整后代码
import os
import pandas as pd
import datetime
from datetime import date

path = r'C:\Users.....\Consumption Rate'
os.chdir(path)

# 过滤目录下的Excel文件,避免读取到文件夹/其他格式文件报错
files = [f for f in os.listdir(path) if f.endswith(('.xlsx', '.xls'))]

# 定义需要读取的三个header位置
target_headers = [5, 11, 21]
row_list = []

for h in target_headers:
    # 存储当前header位置所有文件的读取结果,横向拼接
    current_row = []
    for f in files:
        data = pd.read_excel(f, sheet_name='Charge summary', header=h, usecols="A:B", nrows=1)
        # 把当前文件读取到的2个值展开加入当前行
        current_row.extend(data.values.flatten().tolist())
    row_list.append(current_row)

# 转为DataFrame,可根据需要自行修改列名
df_new = pd.DataFrame(row_list)
# 如果你需要自定义列名可以参考下行格式修改,原代码中的C列不存在,已删除对应重命名逻辑
# df_new.columns = ['Col_1', 'Col_2', 'Col_3', ...]

df_new.to_excel('Cement consumptions.xlsx', index=False)
调整说明
  • 新增了Excel文件过滤逻辑,避免读取到非Excel格式文件导致报错
  • 调整了遍历顺序:优先遍历3个目标header位置,每个位置下遍历所有文件读取数据,横向拼接成完整的一行,最终3个header对应3行结果
  • 替换了pandas已废弃的append方法,改用列表存储结果再转DataFrame,兼容性和运行效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:27:05