首页 > 解决方案 > 将字符串项附加到 Pandas 列中的列表

问题描述

对于熊猫数据框:

Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']

如何将“tag2”附加到标签列表中?

我尝试了以下方法(addtag2 是另一个 df):

df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)

df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))

但他们将字符串附加到列表之外,例如['tag1']、tag2 或 ['tag1']tag2

所需的输出将是:

Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']

标签: pythonpandas

解决方案


这是一个apply派上用场的例子:

df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])

或者你可以做一个 for 循环:

for x in df.Tags: x.append('tag2')

输出:

    Name                Tags
0    One  [tag1, tag3, tag2]
1    Two              [tag2]
2  Three        [tag1, tag2]

推荐阅读