>>> df
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table
small large
foo one 1 4
two 6 NaN
bar one 5 4
two 6 7
我希望输出如上所示,但是得到排序的输出。bar位于foo之上,依此类推。
创建时pivot_table
,索引会自动按字母顺序排序。不仅foo
和bar
,您还可能会注意到small
和large
已排序。如果您想排foo
在最前面,则可能需要sort
再次使用它们sortlevel
。如果您期望此处的示例所示为输出,则进行排序,A
并且C
可能两者都需要。
table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False, sort_remaining=False, inplace=True)
print(table)
输出:
C small large
A B
foo one 1.0 4.0
two 6.0 NaN
bar one 5.0 4.0
two 6.0 7.0
删除索引名称A
,B
以及C
:
table.columns.name = None
table.index.names = (None, None)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句