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

AWS Lambda中Pandas DataFrame无法使用append()或loc添加行的问题

解决AWS Lambda中Pandas DataFrame添加行的AttributeError及列数不匹配问题

问题根源

Lambda环境的Pandas版本为2.0及以上,DataFrame.append()方法已被官方移除,这就是你遇到AttributeError: 'DataFrame' object has no attribute 'append'的原因。本地环境能正常运行是因为使用了低于2.0的Pandas版本。

解决方案

方案1:用pd.concat()替代append()

将新增记录转为DataFrame后与原DataFrame拼接,是官方推荐的替代方式:

df = pd.read_csv(response['Body'], sep=',')
pd.set_option('display.max_columns', None)

first_name = 'Steve'
last_name = 'Jobs'
name = f"{first_name} {last_name}"
firm = 'Apple'
position = 'CEO'
product = 'Macintosh'
date_sent = today
type = 'StreetCat Generated'

# 构造单行DataFrame
new_row = pd.DataFrame([{
    'Name': name,
    'Firm': firm,
    'Position': position,
    'Product': product,
    'Date Sent': date_sent,
    'Type': type
}])

# 拼接并重置索引
df2 = pd.concat([df, new_row], ignore_index=True)
  • ignore_index=True会重置合并后的DataFrame索引,避免因原索引重复导致的问题。

方案2:修正loc添加行的写法

你之前的loc用法错误,原因是将包含字典的列表直接赋值给行,导致列数不匹配。正确写法是直接传入字典:

df = pd.read_csv(response['Body'], sep=',')
pd.set_option('display.max_columns', None)

first_name = 'Steve'
last_name = 'Jobs'
name = f"{first_name} {last_name}"
firm = 'Apple'
position = 'CEO'
product = 'Macintosh'
date_sent = today
type = 'StreetCat Generated'

new_row_dict = {
    'Name': name,
    'Firm': firm,
    'Position': position,
    'Product': product,
    'Date Sent': date_sent,
    'Type': type
}

# 直接用字典赋值到新行
df.loc[len(df)] = new_row_dict
# 若需保留原DataFrame,可先复制:df2 = df.copy(); df2.loc[len(df2)] = new_row_dict
  • len(df)获取当前DataFrame的行数,作为新行的索引位置。
  • 确保字典的键与原DataFrame的列名完全一致,避免列缺失或不匹配。

额外建议

  • 检查Lambda的Pandas版本:在代码中添加print(pd.__version__)即可确认,版本不一致是云端与本地环境差异的常见原因。
  • 尽量避免回退到旧版本Pandas:append()方法已被官方标记为废弃并移除,后续版本不再维护,使用pd.concat()或直接赋值的方式更具兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:42:47