pandas|pandas dataframe pivot_table

一个比较有代表性的例子 参考官网

df=pd.DataFrame({ "value":np.random.randn(36) }, index=pd.date_range('2011-01-01',freq='M',periods=36)) print(df)

结构如下:
pandas|pandas dataframe pivot_table
文章图片

dff=pd.pivot_table(df,index=df.index.month,columns=df.index.year, values='value', # aggfunc='mean' )print(dff) dff=pd.pivot_table(df,index=df.index.month,columns=df.index.year, values='value', aggfunc='sum' )print(dff)

结构如下:
pandas|pandas dataframe pivot_table
文章图片

df1=pd.pivot_table(df,index=df.index.year,values='value', columns=df.index.month,aggfunc='sum') print(df1) print(df1.sum()) print(df1.sum(axis=1)) df1['sum']=df1.sum(axis=1) df1.loc['newr']= df1.sum() print(df1)

【pandas|pandas dataframe pivot_table】pandas|pandas dataframe pivot_table
文章图片


df=pd.pivot_table(df,index=df.index.day,values='value',columns=df.index.month) print(df)

pandas|pandas dataframe pivot_table
文章图片


源码:
import pandas as pd import numpy as npdf=pd.DataFrame({ "value":np.random.randn(36) }, index=pd.date_range('2011-01-01',freq='M',periods=36)) print(df)dff=pd.pivot_table(df,index=df.index.month,columns=df.index.year, values='value', # aggfunc='mean' )print(dff) dff=pd.pivot_table(df,index=df.index.month,columns=df.index.year, values='value', aggfunc='sum' )print(dff) df1=pd.pivot_table(df,index=df.index.year,values='value', columns=df.index.month,aggfunc='sum') print(df1) print(df1.sum()) print(df1.sum(axis=1)) df1['sum']=df1.sum(axis=1) df1.loc['newr']= df1.sum() print(df1) df2=pd.pivot_table(df,index=df.index.year,values='value', aggfunc='mean') print(df2)print("*"*22) df=pd.pivot_table(df,index=df.index.day,values='value',columns=df.index.month) print(df)

    推荐阅读