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

使用pandas向已有DataFrame追加数据写入Excel时覆盖原有内容如何解决

pandas追加写入Excel避免覆盖的修正方案

问题根源

你的代码出现数据覆盖问题的核心原因有两点:

  • 每次运行都新建空白DataFrame作为基底,没有读取Excel文件中已存储的历史数据
  • 用到的df.append()方法在pandas 2.0及以上版本已被官方弃用,兼容性较差

修正后可运行代码

import pandas as pd
import os

# 收集用户输入信息
FirstName = input('你叫什么名字?\n')
LastName = input('你的姓氏是什么?\n')
ageCustomer = int(input('你当前的年龄是多少?\n'))
genderCustomer = input('你的生理性别是?\n')
socialCustomer = int(input('请输入你的社保号或个人纳税识别号(需为6位数字):\n'))
bdDayCustomer = int(input('请输入你的生日日期(仅填数字):\n'))
bdMonthCustomer = int(input('请输入你的生日月份(仅填数字):\n'))
bdYearCustomer = int(input('请输入你的出生年份(需为4位数字):\n'))
InAmountCustomer = int(input('请输入首次存款金额:\n'))

# 构造待新增的行数据
row_to_add = pd.DataFrame({
    'FirstN': [FirstName],
    'LastN': [LastName],
    'Age': [ageCustomer],
    'Gender': [genderCustomer],
    'SSN': [socialCustomer],
    'bdDay': [bdDayCustomer],
    'bdMonth': [bdMonthCustomer],
    'bdyear': [bdYearCustomer],
    'InAmount': [InAmountCustomer],
})

file_path = 'CustomerInfo.xlsx'
# 判断文件是否已存在
if os.path.exists(file_path):
    # 读取已有历史数据
    original_df = pd.read_excel(file_path)
    # 拼接历史数据与新数据,替代已弃用的append方法
    df_final = pd.concat([original_df, row_to_add], ignore_index=True)
else:
    # 文件不存在时直接用新数据作为初始表
    df_final = row_to_add

# 写入完整数据到Excel,不保留pandas自动生成的索引列
with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
    df_final.to_excel(writer, index=False)

print(df_final)

注意事项

  • 运行前需安装依赖库:pip install pandas openpyxl
  • 该方案为单工作表场景优化,直接读取全量数据拼接后重写,比追加写入单个行的方式更稳定,不会出现工作表重复、格式错乱问题
  • 代码已删除原逻辑中无意义的空白df1,避免最终文件出现多余空白行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:36:02