2016-05-01 35 views
1

整理整頓我有熊貓的follwing透視表:透視表

Division    BU/CF  Allocation Key CurrentHC 

0 Central Functions  A   NEF   3 
1      B   NEF   2 
2      C   EXP   1 
3          NEF   4 
4      D   NEF   3 
5 Xerxes    E   NLE   4 
6      F   NLE   1 
7      G   NLE   1 
8      H   NLE   5 

Python的排序明顯的劃分和BU/CF字母。我如何將自己的訂單應用到數據透視表。

所需的輸出:

Division    BU/CF  Allocation Key CurrentHC 
0 Central Functions  D   NEF   3 
1      B   NEF   2 
2      C   EXP   1 
3          NEF   4 
4      A   NEF   3 
5 Xerxes    E   NLE   4 
6      H   NLE   5 
7      G   NLE   1 
8      F   NLE   1 

代碼我用來創建數據透視表:

#Create full report pivot 
report_pivot = pd.pivot_table(full_report, index=["Division","BU/CF", "Allocation Key"], 
         values=["Previous HC", "New Hire", "Resigned", "In", "Out", "Current HC", "Delta"], 

         fill_value=0) 

我設法這樣做是爲了重新排列列:

# Reorderr columns 
cols = [ "Previous HC", "New Hire", "Resigned", "In", "Out","Delta", "Current HC"] 
report_pivot = report_pivot[cols] 

是否有索引類似的方式。特別是 「BU/CF」

*我排除在外,除了當前HC到表中簡化上述

+1

也許thatone幫助:http://stackoverflow.com/questions/10595327/pandas-sort-pivot-table請給出一個完整的代碼和數據,以便我們可以輕鬆地適應一個解決方案。 – tfv

+0

我添加了我用來製作數據透視表 – alpenmilch411

+0

看看你想要的DF的代碼,它絕對不清楚「我自己的訂單」是什麼意思。你能定義排序標準嗎? – MaxU

回答

1

其他列好,你可以做這樣的事情:

In [62]: sort_map = { 
    ....: 'E': 10, 
    ....: 'H': 20, 
    ....: 'G': 30, 
    ....: 'F': 40, 
    ....: } 

In [63]: df.loc[df['Division'] == 'Xerxes', 'BU/CF'].map(sort_map) 
Out[63]: 
5 10 
6 40 
7 30 
8 20 
Name: BU/CF, dtype: int64 

In [64]: idx = df.loc[df['Division'] == 'Xerxes', 'BU/CF'].map(sort_map).sort_values().index 

In [65]: idx 
Out[65]: Int64Index([5, 8, 7, 6], dtype='int64') 

In [66]: df[df['Division'] == 'Xerxes'].reindex(idx) 
Out[66]: 
    Division BU/CF AllocationKey CurrentHC 
5 Xerxes  E   NLE   4 
8 Xerxes  H   NLE   5 
7 Xerxes  G   NLE   1 
6 Xerxes  F   NLE   1 

UPDATE :

從Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers開始。