Pandas:对数据透视表进行排序
发布于 2021-01-29 18:06:01
第一次尝试熊猫,我试图先按照索引对数据透视表进行排序,然后再对一系列值进行排序。
到目前为止,我已经尝试过:
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
按索引然后按值对数据透视表进行排序的正确方法是什么?
关注者
0
被浏览
139
1 个回答
-
这是一个可以做您想要的解决方案:
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方法内置到熊猫中会很好。虽然不确定应该是什么样。