透视表(pivot_table)
实例
1 基本语句
代码:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"])
效果:
2 aggfunc
例子一:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=np.sum)
例子二:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=[np.mean,len])
3 columns
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"], columns=["Product"],aggfunc=[np.sum],fill_value=0)
4 对values应用不同的函数
一对一(value-aggfunc)
pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"], aggfunc={"Quantity":len,"Price":np.sum},fill_value=0)
;
一对多(一个value运用多个函数)
table = pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"], aggfunc={"Quantity":len,"Price":[np.sum,np.mean]},fill_value=0)
5 margins显示合计
pd.pivot_table(df,index=["Manager","Rep","Product"], values=["Price","Quantity"], aggfunc=[np.sum,np.mean],fill_value=0,margins=True)