파이썬
[Python] Pivot Table (피벗테이블)
필경이야
2022. 4. 26. 09:34
[Python] Pivot Table (피벗테이블)
- groupby 집계의 다차원 버전이다.
import numpy as np
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
0 | 0 | 3 | male | 22 | 1 | 0 | 7.25 | S | Third | man | TRUE | Southampton | no | FALSE | |
1 | 1 | 1 | female | 38 | 1 | 0 | 71.2833 | C | First | woman | FALSE | C | Cherbourg | yes | FALSE |
2 | 1 | 3 | female | 26 | 0 | 0 | 7.925 | S | Third | woman | FALSE | Southampton | yes | TRUE | |
3 | 1 | 1 | female | 35 | 1 | 0 | 53.1 | S | First | woman | FALSE | C | Southampton | yes | FALSE |
4 | 0 | 3 | male | 35 | 0 | 0 | 8.05 | S | Third | man | TRUE | Southampton | no | TRUE |
성별과 자석 등급별 생존율
groupby
titanic.groupby(['sex','class'])['survived'].aggregate('mean').unstack()
- unstack()
type(titanic.groupby(['sex','class'])['survived'].aggregate('mean').unstack())
-> pandas.core.frame.DataFrame
no_stack = titanic.groupby(['sex','class'])['survived'].mean()
no_stack
- unstack()함수를 호출하지 않으면 index기준 위->아래로 재구조화된다.
- type(no_stack) => series
nostack.loc['male'].loc['Second']
pivot
titanic.pivot_table('survived',index='sex',columns='class')
- 데이터를 보면 1등석에 탄 여성은 거의 생존했지만 3등석에 탄 남성은 거의 생존하지 못했다.