pandas :对数据透视表进行排序 [英] Pandas: Sort pivot table
本文介绍了 pandas :对数据透视表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一次尝试熊猫,我想先按照索引对数据透视表进行排序,然后再对一系列值进行排序.
Just trying out pandas for the first time, and I am trying to sort a pivot table first by an index, then by the values in a series.
到目前为止,我已经尝试过:
So far I've tried:
table = pivot_table(sheet1, values='Value', rows=['A','B'], aggfunc=np.sum)
# Sorts by value ascending, can't change to descending
table.copy().sort()
table
# The following gives me the correct ordering in values, but ignores index
sorted_table = table.order(ascending=False)
sorted_table
# The following brings me back to the original ordering
sorted_table = table.order(ascending=False)
sorted_table2 = sorted_table.sortlevel(0)
sorted_table2
按索引然后按值对数据透视表进行排序的正确方法是什么?
What's the correct way to sort a pivot table by index then value?
推荐答案
以下是可以满足您需要的解决方案:
Here is a solution that may do what you want:
key1 = table.index.labels[0]
key2 = table.rank(ascending=False)
# sort by key1, then key2
sorter = np.lexsort((key2, key1))
sorted_table = table.take(sorter)
结果如下:
In [22]: table
Out[22]:
A B
bar one 0.698202
three 0.801326
two -0.205257
foo one -0.963747
three 0.120621
two 0.189623
Name: C
In [23]: table.take(sorter)
Out[23]:
A B
bar three 0.801326
one 0.698202
two -0.205257
foo two 0.189623
three 0.120621
one -0.963747
Name: C
将其作为API方法内置到熊猫中会很好.不确定应该是什么样子.
This would be good to build into pandas as an API method. Not sure what it should look like though.
这篇关于 pandas :对数据透视表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文