Reputation: 45
For a pandas dataframe:
Name: Tags:
'One' ['tag1', 'tag3']
'Two' []
'Three' ['tag1']
How can 'tag2' be appended to the tags lists?
I have tried the following (addtag2 is another df):
df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)
and
df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))
But they append the string outside the list eg ['tag1'], tag2 or ['tag1']tag2
The desired output would be:
Name: Tags:
'One' ['tag1', 'tag3', 'tag2']
'Two' ['tag2']
'Three' ['tag1', 'tag2']
Upvotes: 1
Views: 2898
Reputation: 34046
Or you can do this using append
:
df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2') or x)
Output:
Name Tags
0 One [tag1, tag3, tag2]
1 Two [tag2]
2 three [tag1, tag2]
Upvotes: 1
Reputation: 150735
This is an instance where apply
comes handy:
df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])
Or you can do a for loop:
for x in df.Tags: x.append('tag2')
Output:
Name Tags
0 One [tag1, tag3, tag2]
1 Two [tag2]
2 Three [tag1, tag2]
Upvotes: 2