python - 通过列中的标签列表对熊猫数据框行进行分组的有效方法
问题描述
给定一个数据框,如:
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]
我当前的代码有效,但我想知道是否有更有效的方法来做到这一点。例如
- 不需要在列表、数据框和字典之间进行转换,
- 不需要使用 for 循环(可能类似于
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')
解决方案
当我们第一次将流派分成一个列表时会更容易
df['Genre'] = df.Genre.str.split('; ')
df.explode('Genre').groupby('Genre')['Movie'].apply(list)
输出
action [The Avengers]
adventure [The Avengers]
biography [Bohemian Rhapsody, The Imitation Game]
drama [Bohemian Rhapsody, The Imitation Game]
fantasy [Harry Potter]
fiction [Star Trek, Harry Potter]
magic [Harry Potter]
music [Bohemian Rhapsody]
sci-fi [Star Trek, The Avengers]
thriller [The Imitation Game]
推荐阅读
- c# - 在实体框架中 EntityState.Detached 使操作变慢
- swift - 如何在登录页面上制作 firebase 验证凭据
- flutter - 扑。如何在 Sliver 中使用 SliverPersistentHeaderDelegate 管理状态?
- google-forms - 在谷歌表单确认页面上清除提交
- python - 谷歌的地理编码 API 关闭连接没有响应
- node.js - AWS Lambda 上的 Apollo Gateway 无法读取未定义的属性“内容类型”
- bash - Erlang 和 bash 脚本(escript)
- c# - 在 C# 中使用具有多个偏移量的指针
- python - 如何在另一个数据框中找出 Timeindex 的变化?
- vlang - V 的路径中可以有空格吗?