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

如何向Pandas列中的列表追加指定元素?

给DataFrame列表列追加元素的解决方案

要实现给first names列的每个列表末尾添加'joe'的需求,以下是两种简洁的实现方式:

方法1:使用apply函数

通过apply对列中的每个列表执行追加操作:

import pandas as pd

# 初始化DataFrame
df = pd.DataFrame(
[
{'first names' :  ['trey', 'tagg']},
{'first names' :  ['teague', 'tanner']},
]
)

# 给每个列表追加'joe'
df['first names'] = df['first names'].apply(lambda x: x + ['joe'])

执行后得到的DataFrame内容:

first names
0[trey, tagg, joe]
1['teague', 'tanner', joe]

方法2:列表推导式

用列表推导式遍历列元素,直接生成新的列表列:

df['first names'] = [lst + ['joe'] for lst in df['first names']]

关键提醒

你尝试的df['first names'].append('joe')是错误用法——这个方法的作用是给Series新增一行数据,而非修改现有列表的元素,会得到包含原列表和单独字符串'joe'的新Series,不符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:50:24