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

Python中如何给pandas DataFrame添加不同列长的页脚行并导出CSV

Python Pandas 为导出的CSV追加指定格式页脚解决方案

你之前使用loc、append操作失败的核心原因是追加的行长度和DataFrame的列数不匹配,原始DataFrame有6列,页脚仅3个有效值,需要补全剩余空列才能正常追加。以下提供两种兼容Python3.5 + Pandas1.3.4版本的实现方案:


方案1:修改DataFrame后导出(适合需要在DataFrame中显示页脚的场景)

import pandas as pd
import datetime

# 原有业务代码保持不变
statement= 'select firstname,lastname,age,gender,college,university from students;' 
cursor.execute(statement)
result_list = cursor.fetchall();
df = pd.DataFrame(result_list)
print(df)

# 新增页脚构造逻辑
row_total = len(df)
# 生成DDMMYY格式的当前日期
current_date = datetime.datetime.now().strftime("%d%m%y")
# 补全6列对齐,后3列填充空字符串
footer_row = ["ABC", row_total, current_date, "", "", ""]
# 追加到DataFrame末尾
df.loc[len(df)] = footer_row

# 导出CSV,关闭索引和表头输出
df.to_csv("students_output.csv", index=False, header=False)

方案2:直接追加到CSV文件(更推荐,大数据量下性能更高)

不需要修改原DataFrame结构,导出原始数据后直接以追加模式写入页脚:

import pandas as pd
import datetime

# 原有业务代码保持不变
statement= 'select firstname,lastname,age,gender,college,university from students;' 
cursor.execute(statement)
result_list = cursor.fetchall();
df = pd.DataFrame(result_list)

# 先导出原始数据
df.to_csv("students_output.csv", index=False, header=False)

# 追加页脚内容
row_total = len(df)
current_date = datetime.datetime.now().strftime("%d%m%y")
footer_str = f"ABC,{row_total},{current_date}\n"
with open("students_output.csv", "a", encoding="utf-8") as f:
    f.write(footer_str)

注意事项

  • 若固定静态值需要调整,直接替换代码中的ABC即可
  • 日期格式%d%m%y严格对应DDMMYY要求,例如2024年12月7日会输出071224

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:54:01