2016-05-01 34 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开始。