首页 > 解决方案 > 如何找到列的名称以及最大值

问题描述

我有数据(df_movies2)的列:年份、制作公司和该特定年份产生的收入。我想返回每年的最大收入以及生产公司的名称。例如,2016 年 Studio Babelsberg 的收入最高。这是数据

这是我尝试过的

  import pandas as pd 
df_movie2.groupby(['year','production_companies']).revenue.max()

但是,它无法返回每年的所有制作公司的名称。谢谢你的帮助

标签: pythonpython-3.xpandas

解决方案


我不完全确定您希望返回什么。如果您的输出按您想要的方式排序,但您缺少值,那是因为.max()duplicates各自的year. max请参阅编辑 1 以从到升序返回所有值min

如果这是一个排序问题,您希望将值返回maxmin值并且不担心删除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

推荐阅读