如何在Pandas中对数据透视表进行排序 [英] How to sort pivot table in Pandas
本文介绍了如何在Pandas中对数据透视表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是代码:
test = pd.DataFrame({'country':['us','ca','ru','cn','ru','cn','us','ca','ru','cn','us','ca','ru','cn','us','ca'], 'month':[5,6,7,5,6,7,5,5,6,7,5,6,6,5,5,6], 'id':[x for x in range(16)]})
p = test.pivot_table(index=['month', 'country'], aggfunc='count')[['id']]
输出看起来像这样:
我想按id
列对表格进行排序,以使最大的数字显示在顶部,例如:
I'd like to sort the table by the id
column, so that the largest number appear on top like:
id
month country
us 4
5 cn 2
ca 1
推荐答案
您需要 DataFrame.reset_index
,"> c3> :
p1 = p.reset_index()
.sort_values(['month','id'], ascending=[1,0])
.set_index(['month','country'])
print (p1)
id
month country
5 us 4
cn 2
ca 1
6 ca 3
ru 3
7 cn 2
ru 1
因为此解决方案不起作用:(
because this solution does not work :(
p1 = p.sort_index(level='month', sort_remaining=True) \
.sort_values('id', ascending=False)
print (p1)
id
month country
5 us 4
6 ca 3
ru 3
5 cn 2
7 cn 2
5 ca 1
7 ru 1
这篇关于如何在Pandas中对数据透视表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文