import pandas as pd
excelample=pd.DataFrame({'Month':["January","January","January","January",
"February", "February","February","February",
"March","March","March","March"],
'Category':["Transportation","Grocery","Household","Entertainment",
"Transportation","Grocery","Household","Entertainment",
"Transportation","Grocery","Household","Entertainment"],
'Amount':[74.,235.,175.,100.,115.,240.,225.,125.,390.,260.,200.,120.]})
excelample
1.統計指標:每月的各個種類的花費:pivotjavascript
example_pivot=excelample.pivot(index='Category',columns='Month',values='Amount')
example_pivot
example_pivot.sum(axis=1)#計算每一個種類的總和
example_pivot.sum(axis=0)#每月的總和
df=pd.read_csv('./Titanic_Data-master/Titanic_Data-master/train.csv')
df.head()#讀取前幾行數據
2.經過性別索引,船艙的等級分類,統計不一樣性別在不一樣船艙的費用:pivot_table(默認求平均值)css
df.pivot_table(index='Sex',columns='Pclass',values='Fare')#默認求平均值
df.pivot_table(index='Sex',columns='Pclass',values='Fare',aggfunc='max')#求最大
df.pivot_table(index='Sex',columns='Pclass',values='Fare',aggfunc='count')#求計數
pd.crosstab(index=df['Sex'],columns=df['Pclass'])#pd.crosstab和df.pivot_table的count是同樣的效果
3.求不一樣等級的艙位,不一樣性別的獲救機率html
df.pivot_table(index='Pclass',columns='Sex',values='Survived',aggfunc='mean')#求平均值的機率
4.新加一列,計算未成年的,不一樣性別的獲救狀況機率html5
df['Underaged']=df['Age']<=18#新加一列
df.pivot_table(index='Underaged',columns='Sex',values='Survived',aggfunc='mean')#求平均值的機率