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

如何为Pandas DataFrame添加值为字典的新列?

问题:为DataFrame添加值为指定字典的新列

现有字典:

value_students_shop = {'hypermarket': 0.143,
                       'supermarket': 0.125, 
                       'small_shop': 0.15}

示例数据集:

df
col1   col2
1      1
2      2
3      3
4      4

需要为该DataFrame添加新列col3,使每一行的col3值均为上述字典,得到如下结果:

df
col1   col2   col3
1      1      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
2      2      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
3      3      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}
4      4      {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15}

解决方法

方法1:直接赋值(最简单高效)

直接将字典赋值给新列,Pandas会自动把字典广播到每一行:

df['col3'] = value_students_shop

方法2:使用assign()方法

适合需要链式操作的场景:

df = df.assign(col3=value_students_shop)

方法3:用apply()(不推荐,效率较低)

仅作参考,大数据集下不如前两种方法高效:

df['col3'] = df.apply(lambda x: value_students_shop, axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:35:19