1

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

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

or df['Tags'].apply(lambda x: x.append('tag2'))
@QuangHoang it works for me; what do you mean? df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2')) doesn't work, but if you just call the bit after the equals sign it works (the df is modified in place)
@Tom That's true. My apology.
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.