简体   繁体   English

如何根据特定列对 MultiIndex Pandas 数据透视表进行排序

[英]How to sort a MultiIndex Pandas Pivot Table based on a certain column

I am new to Python and am trying to play around with the Pandas Pivot Tables.我是 Python 新手,正在尝试使用 Pandas 数据透视表。 I have searched and searched but none of the answers have been what I am looking for.我已经搜索和搜索,但没有一个答案是我正在寻找的。 Basically, I am trying to sort the below pandas pivot table基本上,我正在尝试对下面的熊猫数据透视表进行排序

import numpy as np
import pandas as pd

df = pd.DataFrame({

"TIME":["FQ1","FQ2","FQ2","FQ2"],
"NAME":["Robert",'Miranda',"Robert","Robert"],
"TOTAL":[900,42,360,2000],
"TYPE":["Air","Ground","Air","Ground"],
"GROUP":["A","A","A","A"]})

pt = pd.pivot_table(data=df,
               values =["TOTAL"], aggfunc = (np.sum),
               index = ["GROUP","TYPE","NAME"],
               columns = "TIME",
               fill_value=0,
               margins = True)

Basically I am hoping to sort the "Type" and the "Name" column based on the sum of each row.基本上我希望根据每行的总和对“类型”和“名称”列进行排序。

The end goal in this case would be "Ground" type appearing first before "Air", and within the "Ground" type, I'm hoping to have Robert appear before Miranda, since his sum is higher.在这种情况下,最终目标是“地面”类型首先出现在“空气”之前,在“地面”类型中,我希望罗伯特出现在米兰达之前,因为他的总和更高。

Here is how it appears now:这是它现在的样子:

                     TOTAL            
TIME                   FQ1   FQ2   All
GROUP TYPE   NAME                     
A     Air    Robert    900   360  1260
      Ground Miranda     0    42    42
             Robert      0  2000  2000
All                    900  2402  3302

Thanks to anyone who is able to help!!感谢任何能够提供帮助的人!!

Try this, because your column header is multiindex, you need to use a tuple to access the colums:试试这个,因为你的列标题是多索引的,你需要使用一个元组来访问列:

pt.sort_values(['GROUP','TYPE',('TOTAL','All')], 
               ascending=[True, True, False])

Output:输出:

                     TOTAL            
TIME                   FQ1   FQ2   All
GROUP TYPE   NAME                     
A     Air    Robert    900   360  1260
      Ground Robert      0  2000  2000
             Miranda     0    42    42
All                    900  2402  3302

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM