python - 如何找到列的名称以及最大值
问题描述
我有数据(df_movies2)的列:年份、制作公司和该特定年份产生的收入。我想返回每年的最大收入以及生产公司的名称。例如,2016 年 Studio Babelsberg 的收入最高。这是数据
这是我尝试过的
import pandas as pd
df_movie2.groupby(['year','production_companies']).revenue.max()
但是,它无法返回每年的所有制作公司的名称。谢谢你的帮助
解决方案
我不完全确定您希望返回什么。如果您的输出按您想要的方式排序,但您缺少值,那是因为.max()
您duplicates
各自的year
. max
请参阅编辑 1 以从到升序返回所有值min
。
如果这是一个排序问题,您希望将值返回max
到min
值并且不担心删除duplicate
production_companies
每个值,year
请参阅编辑 2:
import pandas as pd
d = ({
'year' : ['2016','2016','2016','2016','2016','2015','2015','2015','2015','2014','2014','2014','2014'],
'production_companies' : ['Walt Disney Pictures','Universal Pictures','DC Comics','Twentieth Century','Studio Babelsberg','DC Comics','Twentieth Century','Twentieth Century','Universal Pictures','The Kennedy/Marshall Company','Twentieth Century','Village Roadshow Pictures','Columbia Pictures'],
'revenue' : [966,875,873,783,1153,745,543,521,433,415,389,356,349],
})
df = pd.DataFrame(data = d)
编辑1:
df = df.sort_values(['revenue', 'year'], ascending=[0, 1])
df = df.set_index(['year', 'production_companies'])
输出:
revenue
year production_companies
2016 Studio Babelsberg 1153
Walt Disney Pictures 966
Universal Pictures 875
DC Comics 873
Twentieth Century 783
2015 DC Comics 745
Twentieth Century 543
Twentieth Century 521
Universal Pictures 433
2014 Twentieth Century 389
Village Roadshow Pictures 356
Columbia Pictures 349
The Kennedy/Marshall Company 320
编辑2:
df = df.groupby(['year','production_companies'])[['revenue']].max()
idx = df['revenue'].max(level=0).sort_values().index
i = pd.CategoricalIndex(df.index.get_level_values(0), ordered=True, categories=idx)
df.index = [i, df.index.get_level_values(1)]
df = df.sort_values(['year','revenue'], ascending=False)
输出:
revenue
year production_companies
2016 Studio Babelsberg 1153
Walt Disney Pictures 966
Universal Pictures 875
DC Comics 873
Twentieth Century 783
2015 DC Comics 745
Twentieth Century 543
Universal Pictures 433
2014 Twentieth Century 389
Village Roadshow Pictures 356
Columbia Pictures 349
The Kennedy/Marshall Company 320
推荐阅读
- android - RecyclerView 加载歌曲时间过长
- python - 命令“python setup.py egg_info”失败,错误代码,pip install
- django - path() 和 re_path() 有什么区别?
- javascript - 如何在开发 Rails 应用程序时维护 JavaScript 断点?
- javascript - Node.js 回调函数不起作用
- javascript - node.js & express: req.body 未定义
- python-3.x - seaborn如何设置样式和字体大小
- ios - 以编程方式将 UIView 插入其他视图的顶部
- r - 在 R,apg 包中绘制 SoilProfileCollection 中的贡献分数
- android - 退出firebase android studio