将字符串项附加到列中的列表

2024-04-23 09:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

对于数据帧:

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']

Tags: 数据name标记df列表tagsonethree
2条回答

这是一个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]

或者,您可以使用append执行此操作:

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

输出:

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

相关问题 更多 >