[英]Pandas pivot table Nested Sorting Part 3
Episode 3: 第3集:
In part 2 , we retained the hierarchical nature of the indices while sorting within right-most level. 在第2部分中 ,我们在最右边的级别中进行排序时保留了索引的层次结构性质。 In part 1 , we applied a custom sort to the left-most index level while sorting the values within the right-most index. 在第1部分中 ,我们对最左边的索引级别应用了自定义排序,同时对最右边的索引中的值进行了排序。
Now, I'd like to combine both methods. 现在,我想将两种方法结合起来。
Given the following data frame and resultant pivot table: 给定以下数据框和结果数据透视表:
import pandas as pd
df=pd.DataFrame({'A':['a','a','a','a','a','b','b','b','b'],
'B':['x','y','z','x','y','z','x','y','z'],
'C':['a','b','a','b','a','b','a','b','a'],
'D':[7,5,3,4,1,6,5,3,1]})
df
A B C D
0 a x a 7
1 a y b 5
2 a z a 3
3 a x b 4
4 a y a 1
5 b z b 6
6 b x a 5
7 b y b 3
8 b z a 1
table = pd.pivot_table(df, index=['A', 'B','C'],aggfunc='sum')
table
D
A B C
a x a 7
b 4
y a 1
b 5
z a 3
b x a 5
y b 3
z a 1
b 6
I would like to specify a custom order of 'B'. 我想指定“ B”的自定义顺序。 This seems to work: 这似乎可行:
df['B']=df['B'].astype('category')
df['B'].cat.set_categories(['z','x','y'],inplace=True)
Next, I'd like for the pivot table to keep the order for 'B' specified above while sorting the values 'D' descendingly within each category of 'B'. 接下来,我希望数据透视表保持上面指定的“ B”的顺序,同时在“ B”的每个类别中对值“ D”进行降序排序。
Like this: 像这样:
D
A B C
z a 3
x a 7
a b 4
y b 5
a 1
z b 6
b a 1
x a 5
y b 3
Thanks in advance! 提前致谢!
UPDATE: using pivot_table()
更新:使用pivot_table()
In [79]: df.pivot_table(index=['A','B','C'], aggfunc='sum').reset_index().sort_values(['A','B','D'], ascending=[1,1,0]).set_index(['A','B','C'])
Out[79]:
D
A B C
a x a 7
b 4
y b 5
a 1
z a 3
b x a 5
y b 3
z b 6
a 1
is that what you want? 那是你要的吗?
In [64]: df.sort_values(['A','B','D'], ascending=[1,1,0]).set_index(['A','B','C'])
Out[64]:
D
A B C
a z a 3
x a 7
b 4
y b 5
a 1
b z b 6
a 1
x a 5
y b 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.