具有层次结构列的Pandas数据透视表

时间:2019-03-04 10:53:14

标签: python pandas pivot-table

我需要创建一个数据透视表。我的数据框具有以下结构:

data structure

print (df)
  company team person project unit start   end  num
0     ABC  Dev   John     pr1   BE  date  date    3
1     ABC  Dev    Tim     pr1   FE  date  date    4
2     ABC  Dev  James     pr2   FE  date  date    3

我尝试使用以下熊猫函数:

table = pd.pivot_table(df,
                index=["company","team","person"],
                columns=["project", 'unit'],
                values=["start","end","num"],
                aggfunc={"start": np.min,
                       "end": np.max ,
                       "num": np.sum},
                fill_value=0)
table.columns = table.columns.swaplevel(2, 0).swaplevel(1, 0)

数据已转换为以下数据透视表:

pivot

最后我得到了想要的数据结果,但是格式化是一个问题。我希望数据框采用以下格式:

desired ourcome

是否有一种方法可以通过Pandas数据透视表功能将列转换为层次列?

1 个答案:

答案 0 :(得分:2)

DataFrame.reorder_levelsDataFrame.sort_index一起使用,并按DataFrame.reindex的顺序更改列表:

table = pd.pivot_table(df,
                index=["company","team","person"],
                columns=["project", 'unit'],
                values=["start","end","num"],
                aggfunc={"start": np.min,
                       "end": np.max ,
                       "num": np.sum},
                fill_value=0)

vals = ['start','end','num']
table = table.reorder_levels([1,2,0], axis=1).sort_index(axis=1).reindex(vals, level=2, axis=1)
print (table)
project               pr1                             pr2          
unit                   BE              FE              FE          
                    start   end num start   end num start   end num
company team person                                                
ABC     Dev  James      0     0   0     0     0   0  date  date   3
             John    date  date   3     0     0   0     0     0   0
             Tim        0     0   0  date  date   4     0     0   0