
시각화 : 산점도(Scatter)
수치화 : 상관계수spst.pearsonr
판단 기준 :p-value < 0.05이고|r|이 1에 가까울수록강한 상관관계
plt.scatter(titanic['Age'], titanic['Fare'])
plt.xlabel('Age')
plt.ylabel('Fare')
plt.ylim([0, 100]) # 극단적인 fare를 갖는 값을 빼기위해 y축 범위 조정
plt.show()

sns.pairplot(titanic)
plt.show()

.notnull())하고 적용해야 한다.import scipy.stats as spst
spst.pearsonr(titanic['Age'].notnull(), titanic['Fare'])
# PearsonRResult(statistic=0.10070709787796146, pvalue=0.002616756065905484)
titanic.corr()

sns.heatmap(titanic.corr(),
annot = True, # 상관계수 표기
fmt = '.2f', # 소숫점 자릿수
cmap = 'RdYlBu_r', # 칼라맵
vmin = -1, vmax = 1) # 최소, 최대값 지정
plt.show()

시각화 : 각 범주별 평균 비교 - barplot
수치화 : t-test, ANOVA
판단 기준 :p-value < 0.05이고,|t통계량| > 2혹은|f통계량| > 2~3, 그래프상에서 평균 차이가 크고, 신뢰구간이 좁고 서로 겹치지 않을 때 상관관계가 있음
sns.barplot(x=titanic['Survived'], y=titanic['Age'])
plt.xlabel('Survived')
plt.ylabel('Age')
plt.grid()
plt.show()

# 1. 데이터 전처리 (결측치 처리)
temp = titanic.loc[titanic['Age'].notnull()]
# 2. 범주별로 데이터 저장
died = temp.loc[temp['Survived']==0, 'Age']
survived = temp.loc[temp['Survived']==1, 'Age']
# 3. t-test
spst.ttest_ind(died, survived)
# Ttest_indResult(statistic=2.06668694625381, pvalue=0.03912465401348249)

# 1. 데이터 전처리 (결측치 처리)
temp = titanic.loc[titanic['Age'].notnull()]
# 2. 범주별로 데이터 저장
p1 = temp.loc[temp['Pclass']==1, 'Age']
p2 = temp.loc[temp['Pclass']==2, 'Age']
p3 = temp.loc[temp['Pclass']==3, 'Age']
# 3. ANOVA
spst.f_oneway(p1, p2, p3)
# F_onewayResult(statistic=57.443484340676214, pvalue=7.487984171959904e-24)

시각화 : 교차표(Crosstab) -> 모자이크(mosaic)
수치화 : 카이제곱검정
판단 기준 :p-value < 0.05이고, 전체 평균과 각 범주별 평균의 차이가 크고,카이제곱통계량이 자유도의 2배 이상일 때 상관관계가 있다.
pd.crosstab(titanic['Survived'], titanic['Sex'])

# 컬럼별 비율
pd.crosstab(titanic['Survived'], titanic['Sex'], normalize='columns')

# 행 별 비율
pd.crosstab(titanic['Survived'], titanic['Sex'], normalize='index')

# 전체 비율
pd.crosstab(titanic['Survived'], titanic['Sex'], normalize='all')

from statsmodels.graphics.mosaicplot import mosaic
mosaic(titanic, ['Pclass', 'Survived'])
plt.axhline(titanic['Survived'].mean(), color='r') # 전체 생존율
plt.show()

temp = pd.crosstab(titanic['Pclass'], titanic['Survived'], normalize = 'index')
print(temp)
'''
Survived 0 1
Pclass
1 0.370370 0.629630
2 0.527174 0.472826
3 0.757637 0.242363
'''
temp.plot.bar(stacked=True)
plt.axhline(titanic['Survived'].mean(), color = 'r') # 전체 생존율
plt.show()

범주의 수 - 1각 범주형 변수의 자유도의 곱# 1. 교차표 집계
cross = pd.crosstab(titanic['Survived'], titanic['Pclass'])
print(cross)
print('-------------------------------------------------------')
# 2. 카이제곱검정
spst.chi2_contingency(cross)
'''
Pclass 1 2 3
Survived
0 80 97 372
1 136 87 119
-------------------------------------------------------
Chi2ContingencyResult(statistic=102.88898875696056, pvalue=4.549251711298793e-23, dof=2, expected_freq=array([[133.09090909, 113.37373737, 302.53535354],
[ 82.90909091, 70.62626263, 188.46464646]]))
'''
시각화 : KDE plot, Histogram, Box plot 등
수치화 : 그때그때 다름
# common_norm=False : 각 범주(hue)별로 따로 kde plot을 그린다.
# 그래프 아래 면적 = 1
sns.kdeplot(x='Age', data=titanic, hue='Survived', common_norm=False)
plt.show()

# x에 따른 y의 비율을 비교할 수 있다.
sns.kdeplot(x='Age', data=titanic, hue='Survived', multiple='fill')
# 이 옵션의 경우 전체 평균을 그려주면 비교가 더욱 용이하다.
plt.axhline(titanic['Survived'].mean(), color='r') # 전체 생존율
# 기초통계량을 확인하여 나이의 최대 최소 선을 그어주었다.
plt.axvline(0, color='r')
plt.axvline(80, color='r')
plt.show()

sns.histplot(x='Age', data=titanic, bins=16, hue='Survived', multiple='fill')
plt.axhline(titanic['Survived'].mean(), color='r')
plt.show()

# 최대 최소 나이를 확인한 후 연령대별로 cut
bin = [-np.inf, 10, 20, 30, 40, 50, 60, 70, 80]
label=[0, 10, 20, 30, 40, 50, 60, 70]
titanic['Age_grp'] = pd.cut(titanic['Age'], bins=bin, labels=label)
# plt.rcParams["figure.figsize"]=(15, 6) # 세션 전체의 사이즈가 변경되므로 주의
from statsmodels.graphics.mosaicplot import mosaic
mosaic(titanic, ['Age_grp', 'Survived'])
plt.axhline(titanic['Survived'].mean(), color='r') # 전체 생존율
plt.show()
