将字符串项追加到“熊猫”列中的列表

时间:2020-06-02 16:58:58

标签: python 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']

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:1)

或者您可以使用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]