我需要创建一个数据透视表。我的数据框具有以下结构:
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)
数据已转换为以下数据透视表:
最后我得到了想要的数据结果,但是格式化是一个问题。我希望数据框采用以下格式:
是否有一种方法可以通过Pandas数据透视表功能将列转换为层次列?
答案 0 :(得分:2)
将DataFrame.reorder_levels
与DataFrame.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