2

My dataframe has one colum of type list, it looks something like this:

Genre                                              Band
['deep pop r&b', 'indie r&b', 'r&b', 'trap soul'], Elijah Blake 

I'm iterating the dataframe using iterrows(), but when I get the column value it is a string, how can I can load as a list?

for i, row in df.iterrows():
    artist_genres = row['Genres']  #this is a string
    print(artist_genres)   
    for artist_genre in artist_genres:
        print(artist_genre)        #this prints each character, I want to iterate each genre
5
  • expected output? Commented Nov 4, 2018 at 5:25
  • what about df["Genres"].tolist() Commented Nov 4, 2018 at 5:32
  • artist_genres should be a list, how did you get it as a string? Commented Nov 4, 2018 at 5:37
  • @pygo tolist() returns a list of each character ['[', '\'', 'd', ...] Commented Nov 4, 2018 at 5:41
  • @bakka row['Genres'] returns a string, even if I saved a list in that dataframe Commented Nov 4, 2018 at 5:42

2 Answers 2

4

Use ast.literal_eval:

import ast
df['Genre'] = df['Genre'].apply(ast.literal_eval)
Sign up to request clarification or add additional context in comments.

Comments

2

Use eval to convert a string that is actually a list to list

artist_genres = eval(row['Genres'])

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.