Pandas:排序数据透视表

4

我第一次尝试使用pandas,我想先按索引排序一个透视表,然后再按一个系列中的值排序。

到目前为止,我已经尝试过:

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

如何正确地按照索引和值来排序一个数据透视表(pivot table)?


1
你能举个例子说明你期望的结果是什么样子吗?听起来你想按照'A'级别排序,然后在组内按值排序,是这样吗? - Wes McKinney
1个回答

9
这里有一个可能实现你想要的功能的解决方案:
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

这可以作为pandas的API方法进行构建。不过我不确定它应该长什么样子。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接