我的数据框有一个类型列表列,它看起来像这样:
Genre Band
['deep pop r&b', 'indie r&b', 'r&b', 'trap soul'], Elijah Blake
我正在使用iterrows()迭代数据帧,但是当我获得列值是一个字符串时,如何加载为列表?
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
答案 0 :(得分:4)
import ast
df['Genre'] = df['Genre'].apply(ast.literal_eval)
答案 1 :(得分:2)
使用eval将实际上是列表的字符串转换为列表
artist_genres = eval(row['Genres'])