将字符串项附加到 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']


冉冉说
浏览 120回答 2
2回答

一只斗牛犬

这是一个apply派上用场的例子:df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])或者你可以做一个 for 循环:for x in df.Tags: x.append('tag2')输出:    Name                Tags0    One  [tag1, tag3, tag2]1    Two              [tag2]2  Three        [tag1, tag2]

牧羊人nacy

或者您可以使用append:df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2') or x)输出:    Name                Tags0    One  [tag1, tag3, tag2]1    Two              [tag2]2  three        [tag1, tag2]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python