Getting max values from pandas multiindex dataframe

99封情书 提交于 2019-12-05 14:30:57

groupby + head

df.groupby(level=0).head(1)
Out[1882]: 
id  tOfmAJyI
3   mlNXN       4
5   SSvEP       2
11  mlNXN       2
Name: V, dtype: int64

Or

df.loc[df.groupby(level=0).idxmax()]
Out[1888]: 
id  tOfmAJyI
3   mlNXN       4
5   SSvEP       2
11  mlNXN       2
Name: V, dtype: int64

I had the same problem with my code, instead of using max, sort values by 'ascending = False', then use groupby(level=0).head(1). I have provided the code that worked for me and then a suggestion for your code.

table = pd.pivot_table(df, index= ['Site', 'DayofWeek'], values= ['CTR'])

table = table.sort_values(by = 'CTR', ascending = False)

table.groupby(level=0).head(1)

I first used loc and .apply(max) or idxmax(), however an error occured: 'Indexing a MultiIndex with a DataFrame key is not implemented'. So to avoid this use the suggested method

Your code-

table = df.groupby('id')['tOfmAJyI'].value_counts()

table = table.sort_values(by = 'tOfmAJyI', ascending = False)
table.groupby(level=0).head(1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!