对于熊猫数据框:
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']
答案 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]