import pandas as pd
import numpy as np

df = pd.read_csv("titanic.csv")

# 성별/PCall별/어린이 여부 별 생존율을 확인하고자 할때
# 1. pcalss 를 first second third로 변환
pclass = {
    1:"first",
    2:"second",
    3:"third",
}
df.Pclass= df.Pclass.map(pclass)

# 2. 나이가 12살 이하이면 isChild True인 column생성
df["isChild"]=df.Age <= 12

# 성별 pcalss별 어린이 여부별 생존율 평균
df.groupby(["Sex","Pclass","isChild"]).Survived.mean()
# Sex     Pclass  isChild
# female  first   False      0.978495
#                 True       0.000000
#         second  False      0.911765
#                 True       1.000000
#         third   False      0.504132
#                 True       0.478261
# male    first   False      0.352941
#                 True       1.000000
#         second  False      0.080808
#                 True       1.000000
#         third   False      0.118012
#                 True       0.360000
# Name: Survived, dtype: float64

# 3. 생존율을 surv_rate로 저장한다.
surv_rate = df.groupby(["Sex","Pclass","isChild"]).Survived.mean()

# 멀티컬럼으로 groupby했을때 결과는 multi index로 표시되고, multi index는 튜플로 접근 가능하다.
# 남성 생존율
print("1: ",surv_rate["male"])
# 여성의 second pclass 생존율 (두번째부터 튜플로 접근)
print("2: ",surv_rate[("female","second")])
# 남성의 second pclass, 어른 생존율 (두번째부터 튜플로 접근)
print("3: ",surv_rate[("male","second",False)])   
# 1:  Pclass  isChild
# first   False      0.352941
#         True       1.000000
# second  False      0.080808
#         True       1.000000
# third   False      0.118012
#         True       0.360000
# Name: Survived, dtype: float64
# 2:  isChild
# False    0.911765
# True     1.000000
# Name: Survived, dtype: float64
# 3:  0.08080808080808081


# 멀티 index의 경우 level이 있느네, 자료가 시작되는 가까운 순서로 -1, -2, -3이다.
# 즉 Sex : -3  ,   Pclass: -2   isChild : -1 순서이다.
# unstack과 stack은 대부분 longform, wideform으로 설명되어있는데
# unstack은 multi index 를 column으로, stack은 multi-column index를 index 로 변환한다고 이해하면 된다.

# 4. 어린이 여부를 column으로 변경 (unstack 의 default가 -1이라 unstack만 하면 된다.)
surv_rate.unstack()
#				isChild	False	True
# Sex		Pclass		
# female	first	0.978495	0.000000
# 			second	0.911765	1.000000
# 			third	0.504132	0.478261
# male		first	0.352941	1.000000
# 			second	0.080808	1.000000
# 			third	0.118012	0.360000


# 5. PClass 를 column으로 변경 (indexlevel = -2로 설정)
surv_rate.unstack(-2)
#			Pclass		first	second		third
# Sex		isChild			
# female	False	0.978495	0.911765	0.504132
# 			True	0.000000	1.000000	0.478261
# male		False	0.352941	0.080808	0.118012
# 			True	1.000000	1.000000	0.360000


# 6. 성별을 column으로 변경 (indexlevel = -3로 설정)
surv_rate.unstack(-3)
# 			Sex		female		male
# Pclass	isChild		
# first		False	0.978495	0.352941
# 			True	0.000000	1.000000
# second	False	0.911765	0.080808
# 			True	1.000000	1.000000
# third		False	0.504132	0.118012
# 			True	0.478261	0.360000




# index level을 서로 바꿀수 있다.
# -2로 설정하면 ischild 와 Pcalss 순서변경 (이후 sort_index로 정렬할수 있다.)
surv_rate.swaplevel(-2)
"""
Sex     isChild  Pclass
female  False    first     0.978495
        True     first     0.000000
        False    second    0.911765
        True     second    1.000000
        False    third     0.504132
        True     third     0.478261
male    False    first     0.352941
        True     first     1.000000
        False    second    0.080808
        True     second    1.000000
        False    third     0.118012
        True     third     0.360000
Name: Survived, dtype: float64
"""

# swaplevel -3이면 성별과 isChild순서를 변경
surv_rate.swaplevel(-3)
"""
isChild  Pclass  Sex   
False    first   female    0.978495
True     first   female    0.000000
False    second  female    0.911765
True     second  female    1.000000
False    third   female    0.504132
True     third   female    0.478261
False    first   male      0.352941
True     first   male      1.000000
False    second  male      0.080808
True     second  male      1.000000
False    third   male      0.118012
True     third   male      0.360000
Name: Survived, dtype: float64
"""


# droplevel로 삭제도 가능하다.
# isChild삭제
surv_rate.droplevel([-1,-2])
"""
Sex
female    0.978495
female    0.000000
female    0.911765
female    1.000000
female    0.504132
female    0.478261
male      0.352941
male      1.000000
male      0.080808
male      1.000000
male      0.118012
male      0.360000
Name: Survived, dtype: float64
"""


# groupby 와 unstack은 기본적으로 pivot_table 이나 crosstab결과와 동일하다.
# 아래 3가지 결과가 모두 동일하다.
df.pivot_table(values='Survived', index=["Sex","Pclass"],columns=["isChild"], aggfunc="mean")
pd.crosstab([df.Sex,df.Pclass], df.isChild, values=df.Survived, aggfunc="mean")
surv_rate.unstack()
#				isChild	False	True
# Sex		Pclass		
# female	first	0.978495	0.000000
# 			second	0.911765	1.000000
# 			third	0.504132	0.478261
# male		first	0.352941	1.000000
# 			second	0.080808	1.000000
# 			third	0.118012	0.360000

'전처리' 카테고리의 다른 글

결측치 처리  (0) 2023.06.22
Pandas 구간화 bining(cut, qcut)  (0) 2023.06.21
Pandas groupby secton4 transform  (0) 2023.06.20
Pandas groupby section3 (agg)  (0) 2023.06.20
Pandas groupby section2(Multi Key)  (0) 2023.06.20

+ Recent posts