如何向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
相关产品推荐
相关产品推荐

