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 dataframe pivot_table_第1张图片

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 dataframe pivot_table_第2张图片

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 dataframe pivot_table_第3张图片

 

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

pandas dataframe pivot_table_第4张图片

 

源码:

import pandas as pd
import numpy as np

df=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)


你可能感兴趣的:(pandas,pivot_table)