Get value as list in pandas

3262 views python

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
    for artist_genre in artist_genres:
        print(artist_genre)        #this prints each character, I want to iterate each genre

answered question

expected output?

what about df["Genres"].tolist()

artist_genres should be a list, how did you get it as a string?

@pygo tolist() returns a list of each character ['[', '\'', 'd', ...]

@bakka row['Genres'] returns a string, even if I saved a list in that dataframe

2 Answers


Use ast.literal_eval:

import ast
df['Genre'] = ast.literal_eval(df['Genre'])

posted this

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

artist_genres = eval(row['Genres'])

posted this

Have an answer?


Please login first before posting an answer.