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

向pandas空DataFrame添加字典遇警告与错误,求解决方案

问题原因分析

  1. append方法警告:pandas已正式弃用append()方法,后续版本会彻底移除,官方明确推荐使用pd.concat()替代。
  2. from_dict报错:你的字典中所有值都是单个标量,pd.DataFrame.from_dict()默认将字典键作为列名,但此时没有行索引信息,因此抛出必须传入索引的错误。

正确解决方案

方案1:将字典转为单行DataFrame后用concat拼接

这是最直观的方式,把字典放进列表即可生成单行DataFrame,再与原DataFrame拼接:

# 注意:不要用dict作为变量名,这是Python内置类型,易引发冲突
data_dict = {
    'city_name': 'Ixelles',
    'type_of_property': 0,
    'price': 0,
    'number_of_rooms':2, 
    'house_area':120, 
    'fully_equipped_kitchen':1,
    'open_fire':0,
    'terrace':1,
    'garden':0, 
    'surface_of_the_land':120,
    'number_of_facades':1,
    'swimming_pool':0,
    'as new':0,
    'good':0,
    'just renovated':1,
    'to be done up':0,
    'to renovate':0,
    'to restore':0,
    'unknown':0
}
# 生成单行DataFrame
new_row = pd.DataFrame([data_dict])
# 拼接至原DataFrame
df_predict = pd.concat([df_predict, new_row], ignore_index=True)

方案2:用from_dict指定orient参数生成单行DataFrame

如果一定要使用from_dict,可指定orient='index'(将字典键作为行索引),再转置为列的形式后拼接:

new_row = pd.DataFrame.from_dict(data_dict, orient='index').T
df_predict = pd.concat([df_predict, new_row], ignore_index=True)

额外提醒

避免使用dict作为变量名,它是Python的内置类型,会覆盖原有功能,导致后续代码出现未知问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:40:25