[英]Pandas pivot table with hierarchical columns
我需要創建一個數據透視表。 我的數據框具有以下結構:
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數據透視表功能將列轉換為分層列?
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.