给定如下数据帧:
df = pd.DataFrame(
{
'Movie':
[
'Star Trek',
'Harry Potter',
'Bohemian Rhapsody',
'The Imitation Game',
'The Avengers'
],
'Genre':
[
'sci-fi; fiction',
'fantasy; fiction; magic',
'biography; drama; music',
'biography; drama; thriller',
'action; adventure; sci-fi'
]
}
)
我想按“流派”列中的各个标签分组,并收集电影列表,如:
0
magic [Harry Potter]
sci-fi [Star Trek, The Avengers]
fiction [Star Trek, Harry Potter]
drama [Bohemian Rhapsody, The Imitation Game]
fantasy [Harry Potter]
music [Bohemian Rhapsody]
thriller [The Imitation Game]
action [The Avengers]
biography [Bohemian Rhapsody, The Imitation Game]
adventure [The Avengers]
我目前的代码可以工作,但我想知道是否有更有效的方法来实现这一点。 例如
groupby
)genre = df['Genre'].apply(lambda x: str(x).split("; ")).tolist()
movie = df['Movie'].tolist()
data = dict()
for m,genres in zip(movie, genre):
for g in genres:
try:
g_ = data[g]
except:
data[g] = [m]
else:
g_.append(m)
for key,value in data.items():
data[key] = [data[key]]
output = pd.DataFrame.from_dict(data, orient='index')
当我们第一次将流派划分成一个列表时,这会更容易
输出
相关问题 更多 >
编程相关推荐