1

I have a df that looks like this which top 3 rows look like this: df.head()

                Category    Key_words
     Title      
- 14 Nyhederne  kortfilm    (direkte, fyringer)
- 6 Nyhederne   kortfilm    (med, af)
- 6 Nyhederne   nyheder     (med, nã)

The Category is a string, and I would like to append that word inside the list of Key_words. I have tried append, combine, etc etc but I cant make it workl...

I want to create a new column bag_of_words for my output, like this:

                Category    Key_words            bag_of_words
     Title      
- 14 Nyhederne  kortfilm    (direkte, fyringer)  (kortfilm, direkte, 
                                                  fyringer)
- 6 Nyhederne   kortfilm    (med, af)            (kortfilm, med, af)
- 6 Nyhederne   nyheder     (med, nã)            (nyheder, med, nã)

I tried df.Key_words.join([df.Category]) but I get:

AttributeError: 'Series' object has no attribute 'join'

2
  • Are the values in your Key_words column type list? Commented Apr 25, 2019 at 8:39
  • yes, key_words is a list Commented Apr 25, 2019 at 8:44

1 Answer 1

1

If values are tuples in Key_words columns:

df['bag_of_words'] = [(a,) + b for a, b in zip(df['Category'], df['Key_words'])]

If values are lists in Key_words column:

df['bag_of_words'] = [[a] + b for a, b in zip(df['Category'], df['Key_words'])]
print (df)
            Title  Category            Key_words  \
0  - 14 Nyhederne  kortfilm  [direkte, fyringer]   
1   - 6 Nyhederne  kortfilm            [med, af]   
2   - 6 Nyhederne   nyheder            [med, ns]   

                    bag_of_words  
0  [kortfilm, direkte, fyringer]  
1            [kortfilm, med, af]  
2             [nyheder, med, ns]  
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for your fast reply jezrael. It seems that the key_words is a list, and the code you gave me gives me this error: TypeError: must be str, not list`
@AlexS - changed solution
Yes! It works now, thank you so much for you fast reply. I am mostly working with R, but now I have this Python assignment in uni. It seems that you have a lot of experience jezrael, could you recommend me a few Python courses for me to start learning the language? Thank you in advance
By the way, I need to wait 6 more mins to accept your answer
@AlexS - You can check this tutorials.
|

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.