pandas Pivot_Table保留顺序 [英] Pandas pivot_table preserve order
本文介绍了 pandas Pivot_Table保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> 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之上,依此类推.
I want the output to be as shown above, but I get a sorted output. bar comes above foo and so on.
推荐答案
在创建pivot_table
时,索引是按字母顺序自动排序的.不仅foo
和bar
,您还可能会注意到small
和large
已排序.如果要在顶部放置foo
,则可能需要使用sortlevel
再次sort
.如果您希望像此处的示例中那样进行输出,然后可能都需要同时对A
和C
进行排序.
While creating pivot_table
, the index is automatically sorted alphabetically. Not only foo
and bar
, you may also notice small
and large
is sorted. If you want foo
on top, you may need to sort
them again using sortlevel
. If you are expecting output as in example here, then sorting on A
and C
both may be needed.
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)
这篇关于 pandas Pivot_Table保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文