在Pandas中向列内的列表追加值的实现方法
实现DataFrame中c列值追加至notes列列表的方法
核心方案
针对需求,有两种高效的实现方式:
方法一:使用
apply结合lambda函数
适合小体量DataFrame,代码直观易读:import pandas as pd # 假设你的DataFrame变量名为df df['notes'] = df.apply(lambda row: row['notes'] + [row['c']], axis=1)方法二:列表推导式
处理大数据量时性能更优,避免apply的循环开销:df['notes'] = [notes_list + [c_val] for notes_list, c_val in zip(df['notes'], df['c'])]
效果验证
假设原始数据结构如下:
| a | b | c | notes |
|---|---|---|---|
| 1 | 2 | 3 | ['x', 'y'] |
| 4 | 5 | 6 | ['p', 'q', 'r'] |
执行上述任意一种方法后,得到预期结果:
| a | b | c | notes |
|---|---|---|---|
| 1 | 2 | 3 | ['x', 'y', 3] |
| 4 | 5 | 6 | ['p', 'q', 'r', 6] |
内容的提问来源于stack exchange,提问作者GeekGroot
相关产品推荐
相关产品推荐

