You need to enable JavaScript to run this app. Python Pandas如何实现DataFrame追加?append后主数据框为空的解决方法
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas如何实现DataFrame追加?append后主数据框为空的解决方法

问题根本原因
  • 第一类核心操作失误:pd.DataFrame.append() 没有原地修改特性。该方法执行后不会改动原DataFrame的内容,只会返回一个追加完成后的全新DataFrame对象。你如果只单独写master.append(temporary)而不将返回值重新赋值给master变量,原master自始至终都不会有任何内容变更,自然始终是空的。
  • 第二类初始化失误:如果定义列集合时,直接把列名列表赋值给master变量,没有调用pd.DataFrame(columns=列集合)生成真正的DataFrame结构,后续所有追加操作都会因为类型不匹配完全失效。
  • 第三类版本适配问题:pandas 1.4.0及以上版本已经正式弃用append()方法,长期使用会出现运行告警,后续大版本中该方法会被直接移除,官方统一推荐使用pd.concat()实现多DataFrame的纵向拼接。

推荐的正确实现方案

相比循环内反复调用append/concat,更高效、更稳定的实现逻辑是:

  1. 初始化带目标列的空master DataFrame
  2. 循环读取工作表做筛选时,把每一轮筛选出的符合条件的行存入临时列表,不在循环内做拼接操作(避免循环中重复生成完整DataFrame带来的性能损耗)
  3. 所有循环结束后,一次性完成临时列表内所有数据与master的拼接
  4. 空值判断使用pandas原生isna()方法,兼容Excel读取的NaN、空字符串等多种空值场景,避免筛选逻辑失效
import pandas as pd
from IPython.display import display

# 定义目标列集合
target_columns = ['Development id', 'Development Name', 'Integrated Development', 'Developer id', 
               'Developer', 'Ultimate Developer id', 'Ultimate Developer', 'Development Type', 
               'Sub Development Type', 'Joint-Venture', 'Year Completed', 'Latitude', 'Longitude', 
               'No of Floors', 'No of Rooms', 'No of Units/Residences/Lots', 'Gross Floor Area (SQM)', 
               'Gross Leasable Area', 'Lot Area (SQM)', 'Region', 'City/Municipality', 'CBD', 
               'Parking vehicles', 'Min. Price per SQM 2020', 'Max. Price per SQM 2020', 
               'Monthly Min. Rent per SQM 2020', 'Monthly Min Rent per SQM 2020']

# 正确初始化空的master DataFrame
master = pd.DataFrame(columns=target_columns)
# 存储每轮筛选结果的临时列表
temp_data_container = []

# 遍历待读取的工作表列表
for sheet in my_list:
    # 读取对应工作表内容
    sheet_df = pd.read_excel("Template For Developer Footprint.xlsx", sheet_name=sheet)
    # 筛选符合条件的行
    temporary = sheet_df[
        (sheet_df["Development Type"] == "Hotel & Resort")
        & (sheet_df["Development id"].isna())
    ]
    # 打印当前筛选内容
    display(temporary)
    # 将筛选结果存入临时容器
    temp_data_container.append(temporary)

# 所有循环结束后一次性拼接所有数据
master = pd.concat(
    [master] + temp_data_container,
    ignore_index=True # 重置连续索引,避免拼接后出现重复索引
)

原append写法的最小修正方案

如果暂时不想调整为pd.concat的逻辑,只需要对原代码做两处修正即可解决问题:

  1. 初始化master时不要直接赋值列名列表,要生成真正的空DataFrame:master = pd.DataFrame(columns=你的列集合列表)
  2. 调用append时,必须把返回值重新赋值给master变量,不能只单独写一行append代码:

    错误写法:master.append(temporary)
    修正写法:master = master.append(temporary, ignore_index=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 00:54:10