簡體   English   中英

熊貓:排序樞軸表

[英]Pandas: Sort pivot table

只是第一次嘗試大熊貓,我試圖先通過索引對數據透視表進行排序,然后按系列中的值進行排序。

到目前為止,我已經嘗試過:

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

按索引排序數據透視表的正確方法是什么?

這是一個可以做你想要的解決方案:

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方法構建到pandas中。 不知道它應該是什么樣子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM