python - pandas:按两列分组,然后按第三列的值排序
问题描述
我有以下行:
genre_df.groupby(['release_year', 'genres']).vote_average.mean()
这给了我以下信息:
release_year genres
1960 Action 6.950000
Adventure 7.150000
Comedy 7.900000
Drama 7.600000
Fantasy 7.300000
History 6.900000
Horror 8.000000
Romance 7.600000
Science Fiction 7.300000
Thriller 7.650000
Western 7.000000
1961 Action 7.000000
Adventure 6.800000
Animation 6.600000
Comedy 7.000000
Crime 6.600000
Drama 7.000000
Family 6.600000
History 6.700000
Music 6.600000
Romance 7.400000
War 7.000000
...
我希望看到的是按发行年份和流派分组的 df,但首先按最高投票平均值排序。
又名:
release_year genres
1960 Horror 8.000000
Comedy 7.900000
Action 6.950000
Thriller 7.650000
Drama 7.600000
Romance 7.600000
Fantasy 7.300000
Science Fiction 7.300000
Adventure 7.150000
Western 7.000000
History 6.900000
如何做到这一点?
解决方案
0.23.0+的解决方案- 首先创建一列DataFrame
,to_frame
然后sort_values
:
df = df.to_frame().sort_values(['release_year','vote_average'], ascending=[True, False])
print (df)
vote_average
release_year genres
1960 Horror 8.00
Comedy 7.90
Thriller 7.65
Drama 7.60
Romance 7.60
Fantasy 7.30
Science Fiction 7.30
Adventure 7.15
Western 7.00
Action 6.95
History 6.90
1961 Romance 7.40
Action 7.00
Comedy 7.00
Drama 7.00
War 7.00
Adventure 6.80
History 6.70
Animation 6.60
Crime 6.60
Family 6.60
Music 6.60
对于旧版本的 pandas 是必要的reset_index
,并且set_index
:
df = (df.reset_index()
.sort_values(['release_year','vote_average'], ascending=[True, False])
.set_index(['release_year','genres']))
推荐阅读
- php - 如何在一个请求中返回图像和文本
- android - 如何使用深度链接?
- python - 弹性搜索与 python
- sql - 如何在 Access 查询中显示没有键的记录
- bash - 在特定时间添加底层音频和音频
- laravel - JWT 令牌在 Vuejs SPA 中的某些 PC 上不起作用
- cassandra - 添加新的 Cassandra 节点时,现有角色无法登录该节点
- asp.net - 如何使用 azure 数据库连接字符串更改实体框架(模型优先应用程序)的连接字符串?
- flyway - 如何在同一个模式中支持多个 flyway 迁移?
- ios - 是否有任何解决方法可以避免 SFSafariViewController 隐藏固定位置的标题?