熊猫:排序枢轴表

时间:2012-05-15 06:34:03

标签: python 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

通过索引然后按值对数据透视表进行排序的正确方法是什么?

1 个答案:

答案 0 :(得分: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方法会很好。不知道它应该是什么样子。

相关问题