데이터 분석을 시작하기전, 다루고 있는 데이터를 철저히 이해해야 한다.
다루는 데이터에 대한 철저한 이해는 분석 방법을 선택하고 적용하는 것의 기반이 된다.
고려해야할 특성들은 아래와 같다.
- 데이터 타입 : 데이터의 타입이 이산적인지, 비율인지, 명목형 등등 중에서 어떤 것인지 아는것은 올바른 분석법을 선택하는 데에 핵심이다.
- 데이터의 분산 : 분산의 범위와 모양은 어떤 분석이 적절한지 선택하는 데에 큰 영향을 미친다.
- 변수들간의 관계 : 변수들간의 상관관계 역시 올바른 분석법을 선택하는데 가이드의 역할을 한다.
데이터의 타입은 크게 Univariate Data(단변량 데이터)와 Multivariate Data(다변량 데이터)로 나뉜다.
이 두가지 분석 모두에서 올바르게 데이터의 특성을 이해하는 것은 분석법과 분석기술 선택에 있어서 중요하다.
아래에 두가지 방법론에 대해 설명한다.
단일 변수 분석, 데이터를 설명하고 그 안에서 발생하는 패턴을 찾는 것이 주 목적이다.
주요 유형은 다음과 같다.
- 데이터 예시 : 선호하는 애완동물의 종류에 대한 Survey 답변
- 데이터 포인트 : {개, 고양이, 앵무새, 이구아나}
- 분석 : 각 데이터의 갯수/퍼센트 파악
- 데이터 예시 : 상품에 대한 평점(1점~5점)
- 데이터 포인트 : {1 (Very Unsatisfied), 2 (Unsatisfied), 3 (Neutral), 4 (Satisfied), 5 (Very Satisfied)}
- 분석 : Median rating or distribution of satisfaction levels.
- 데이터 예시 : 각 도시별 현재 온도
- 데이터 포인트 : {New York: 20°C, Los Angeles: 25°C, Chicago: 15°C, Miami: 30°C}
- 분석 : 평균 온도, 온도 분포, 각 도시별 온도 비교
- 데이터 예시 : 학생들의 키 조사
- 데이터 포인트 : {170 cm, 160 cm, 165 cm, 175 cm, 180 cm}
- 분석 : 평균 키, 키 분포, 가장 큰 키와 작은 키 식별
- 데이터 예시 : 성별, 선호하는 애완동물 유형, 만족도 평가를 포함한 설문조사 응답
- 데이터 포인트 : 각 응답자의 데이터는 {Gender: Female, Pet Preference: Cat, Satisfaction: 4 (Satisfied)} 와 같을 수 있다.
- 분석 : 성별과 애완동물 선호 사이의 관계 또는 다양한 애완동물 선호도 간의 만족도 수준 확인.
- 데이터 예시 : 환자의 나이, 성별, 혈압, 질병 분류
- 데이터 포인트 : 환자 기록은 {나이: 45, 성별: 남성, 혈압: 120/80 mmHg, 질병: 고혈압}일 수 있다.
- 분석 : 나이, 혈압, 고혈압의 유병률 사이의 상관관계 조사; 성별에 따른 차이 분석
- 데이터 예시 : 회사의 연간 수익, 이익률, 산업 분류
- 데이터 포인트 : 회사 데이터는 {수익: $10M, 이익률: 15%, 산업종류: 기술산업}과 같을 수 있다.
- 분석 : 산업별 재무 건전성 분석; 기술 및 비기술 분야 간의 수익과 이익률 비교
- 데이터 예시 : 다양한 지역의 월 평균 온도, 강수량, 식생 유형
- 데이터 포인트 : 지역 데이터는 {온도: 22°C, 강수량: 120 mm, 식생: 숲}일 수 있다.
- 분석 : 기후 패턴 및 그것이 식생 유형에 미치는 영향 연구; 지역 간 환경 요인 비교
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
import seaborn as sns
import warnings
# Data load(titanic)
df_titanic=sns.load_dataset('titanic')
# Understanding data
print(df_titanic.head())
print(df_titanic.info())
print(df_titanic.describe())



각 컬럼별 분포를 간단히 확인할때 사용한다.
# DataFrame[column name].value_counts()
print(df_titanic['survived'].value_counts()) # 0:Dead, 1:survived
print(df_titanic['sex'].value_counts()) # male/female
print(df_titanic['age'].value_counts())
print(df_titanic['fare'].value_counts())
print(df_titanic['class'].value_counts()) # First, second, third
print(df_titanic['who'].value_counts()) # man, woman, child

실제 데이터셋 각 컬럼의 설명은 아래와 같다.
- Survived: 생존 여부 (0 = 사망, 1 = 생존)
- Pclass: 객실 등급 (1 = 1등석, 2 = 2등석, 3 = 3등석)
- Sex: 성별 (male = 남성, female = 여성)
- Age: 나이
- SibSp: 동반한 형제자매/배우자 수
- Parch: 동반한 부모/자녀 수
- Fare: 요금
- Embarked: 탑승 항구 (C = 셰르부르, Q = 퀸스타운, S = 사우샘프턴)
- Class: 객실 등급 (First = 1등석, Second = 2등석, Third = 3등석)
- Who: 인물 구분 (man, woman, child)
- Adult_Male: 성인 남성 여부 (True = 성인 남성, False = 그 외)
- Deck: 객실 번호 첫 글자 (A, B, C, D, E, F, G)
- Embark_Town: 탑승지 명칭 (Cherbourg, Queenstown, Southampton)
- Alive: 생존 여부 (no = 사망, yes = 생존)
- Alone: 혼자 탑승 여부 (True = 혼자 탑승, False = 가족 동반)
# (8) Fares by age
sns.scatterplot(x='age', y='fare', data=df_titanic)
plt.show()

# (8) Fares by age (men and women)
sns.scatterplot(x='age', y='fare', hue='sex', data=df_titanic)
plt.show()

25% quantile (Q1, 1사분위수) : 하위 25%의 데이터가 이 값 이하이고, 상위 75%가 이 값 이상이다.
50% quantile (Q2, 2사분위수) : 짝수 개의 데이터가 있는 경우 중앙에 위치한 두 값의 평균이다. 중앙 값이라고도 불린다.
75% quantile (Q3, 3사분위수) : 하위 75%의 데이터가 이 값 이하이고, 상위 25%가 이 값 이상이다.
# 'fare' 컬럼의 3사분위수(Q3, 하위 75% 지점의 값)를 계산
fare_q3 = df_titanic['fare'].quantile(q=0.75)
# 'fare' 컬럼의 1사분위수(Q1, 하위 25% 지점의 값)를 계산
fare_q1 = df_titanic['fare'].quantile(q=0.25)
# 'fare'의 IQR(Interquartile Range, 사분위수 범위)을 계산
# Q3에서 Q1을 뺀 값으로, 데이터의 중간 50% 범위를 나타낸다.
fare_iqr = fare_q3 - fare_q1
# df_titanic['fare']의 값들이 fare_iqr의 4배한 값안에 들어가는지 검사
condition = df_titanic['fare'] <= 4*fare_iqr
# 검사 범위 안에 들어가는 값으로 새로운 dataframe 선언
new_df_titanic = df_titanic[condition]
sns.scatterplot(x='age', hue='sex', y='fare', data=new_df_titanic)

data_path = "4.csv"
data = pd.read_csv(data_path)
time_column = data["Time"]
sns.lineplot(data=data, x = "Time", y = "1")


최소한 하나의 데이터가 categorical 데이터일때 시각화에 사용된다.
범주형 데이터를 그리는 여러 함수에 접근할 수 있는 figure-level 함수이다.
막대를 사용하여 각 범주형 구간에서 관측치의 수를 보여준다.
# (2-1) Number of people in each room class
sns.catplot(x='class' ,kind='count', data=df_titanic)
plt.show()

# (2-2) Number of men, women, and children by room class
sns.catplot(x='class',hue='who', kind='count',data=df_titanic)
plt.show()

# (2-3) Number of people in each room class by survival status
sns.catplot(x='class', hue='survived', kind='count', data=df_titanic)
plt.show()

# (2-myself) Number of people in each room class by survival status
sns.catplot(x='survived', hue='class', kind='count', data=df_titanic)
plt.show()

생존 유무별 클래스를 파악할 수 있다. 하지만 직접적인 비율을 보기는 힘든데, 그럴경우에 histplot을 이용하면 직접적인 비율 파악이 쉬워진다.(게시글에서 '2-4' 검색)
barplot()
범주형 변수의 각 카테고리에 대해 수치형 변수의 평균(또는 다른 추정치)을 오차 막대와 함께 표시한다.
# (3) Average age and deviation by room class
sns.catplot(x='class', y='age', kind='bar', data=df_titanic)

# (4) Proportion of Survivors and Dead (bar vs. pie)
fig, axes = plt.subplots(ncols=2)
df_titanic["survived"].value_counts().plot(kind = "bar", ax=axes[0])
df_titanic["survived"].value_counts().plot(kind = "pie", autopct='%1.1f%%', ax=axes[1])
plt.show()

# (5) boxplot
# (5-1) Age distribution of survivors and dead
fig, axes = plt.subplots(ncols=2)
sns.boxplot(x='survived',y='age',data=df_titanic, ax=axes[0])
# (5-2) Age distribution of men, women and children
sns.boxplot(x='who',y='age',data=df_titanic,ax=axes[1])
plt.show()

# (5-3) Lab: Fare distribution according to room class
sns.catplot(x='class',y='fare',kind='box',data=df_titanic)
plt.show()

# (5-4) Remove the outliers
fare_q3 = df_titanic['fare'].quantile(q=0.75)
fare_q1 = df_titanic['fare'].quantile(q=0.25)
fare_iqr= fare_q3 -fare_q1
condition = df_titanic['age'] <= 4*fare_iqr
new_df_titanic= df_titanic[condition]
sns.boxplot(data=new_df_titanic, x='survived', y='age')
plt.show()

# (6-1) Age distribution of men, women and children
sns.catplot(x='who',y='age',kind='violin',data=df_titanic)
plt.show()

# (6-2) lab: Fare distribution of survivors and dead
sns.catplot(x='survived',y='fare',kind='violin',data=new_df_titanic)
plt.show()

# (6-3) lab: Fare distribution of survivors and dead after removing outliers
fare_q3 = df_titanic['fare'].quantile(q=0.75)
fare_q1 = df_titanic['fare'].quantile(q=0.25)
fare_iqr= fare_q3 -fare_q1
condition = df_titanic['fare'] <= 4*fare_iqr
new_df_titanic= df_titanic[condition]
sns.catplot(x='survived',y='fare',kind='violin',data=new_df_titanic)
plt.show()

Distribution plot은 데이터셋의 분포를 시각화하기 위해 설계된 plot이다.
단변량 데이터셋의 분포를 히스토그램으로 시각화하고, 데이터에 커널 밀도 추정(KDE)을 적용할 수도 있다.
# Distribution of Age
sns.histplot(data=df_titanic, x='age')
plt.show()

# (2-4) Number of survivors and dead by room class
sns.histplot(x='class', hue='survived', multiple='stack', shrink=.5, data=df_titanic)
plt.show()

커널 밀도 추정을 플로팅하는 방법으로, 연속적인 확률 변수의 확률 밀도 함수를 추정한다.
두 변수 간의 이변량(또는 결합된) 관계와 각각의 단변량(또는 한계적) 분포를 별도의 축에서 보여주는 멀티 패널 그림을 생성한다.
# (10) jointplots(fares by ages, -outliers)
sns.jointplot(x='age', y='fare', data=new_df_titanic)
sns.jointplot(x='age', y='fare', hue='sex', data=new_df_titanic)
plt.show()


# (10) jointplots(fares by ages, -outliers)
sns.jointplot(x='age', y='fare', kind='hex',data=new_df_titanic)
sns.jointplot(x='age', y='fare', kind='reg',data=new_df_titanic)
plt.show()


# (10) jointplots(fares by ages, -outliers)
sns.jointplot(x='age', y='fare', hue='sex', kind='hist',data=new_df_titanic)
sns.jointplot(x='age', y='fare', hue='sex', kind='kde',data=new_df_titanic)
plt.show()


# (10) jointplots(fares by ages, -outliers)
sns.jointplot(x='age', y='fare', hue='who', kind='kde',data=new_df_titanic)
sns.jointplot(x='age', y='fare', hue='class', kind='kde',data=new_df_titanic)
plt.show()


매트릭스 플롯은 데이터를 색상 인코딩된 행렬로 플로팅하고, 여러 변수 간의 관계를 시각화하는데 유용하다.
데이터를 색상 인코딩된 행렬로 시각화하여, 변수 간의 상관관계를 보여주거나 혼동 행렬을 표시하는 데 도움이 된다.
hierarchical clustering(계층적 클러스터링)을 수행하고 클러스터링된 데이터의 히트맵을 표시하여, 데이터 구조에 대한 인사이트를 제공한다
변수들 사이의 선형 관계를 시각화하는 데 사용된다.
산점도를 그리고 그 위에 선형 회귀 모델을 그린다.
# (9) reglot& lmplot
sns.regplot(x='age', y='fare', data=new_df_titanic)

regplot()과 FacetGrid를 결합한 figure-level 함수로, 데이터셋의 다양한 하위 집합에 걸쳐 선형 회귀 모델을 플로팅할 수 있게 해준다.
sns.lmplot(x='age', y='fare', hue='sex',data=new_df_titanic)

Seaborn은 데이터의 다양한 하위 집합을 비교하는 데 유용한 여러 개의 서브플롯을 포함한 그림을 생성하는 함수를 제공한다.
데이터셋 내의 쌍대 관계를 플로팅한다. 기본적으로 이 함수는 데이터 내의 각 변수가 단일 행에 걸쳐 y축에, 단일 열에 걸쳐 x축에 공유되도록 축 그리드를 생성한다.
# (11) pairplots
sns.pairplot(new_df_titanic,
x_vars=['survived','age','fare','class','who','sex'],
y_vars=['survived','age','fare','class','who','sex'],
kind='scatter',
height=1.5)
plt.show()

# (11) pairplots
sns.pairplot(new_df_titanic,
x_vars=['survived','age','fare'],
y_vars=['survived','age','fare'],
kind='scatter',
hue='sex',
height=1.5)
plt.show()

# (11) pairplots
sns.pairplot(new_df_titanic,
x_vars=['survived','age','fare'],
y_vars=['survived','age','fare'],
kind='hist',
hue='sex',
height=1.5)
plt.show()

# (11) pairplots
sns.pairplot(new_df_titanic,
x_vars=['survived','age','fare'],
y_vars=['survived','age','fare'],
kind='kde',
hue='class',
height=1.5)
plt.show()

이들은 다른 변수들에 대한 조건을 기반으로 다중 플롯 그리드를 생성할 수 있는 클래스이다. PairGrid는 PairPlot의 불편함을 해소하기 위해 만들어졌으며, 가장 큰 차이점은 각 시각화 도구를 대각선의 상단과 하단에 적용할 수 있다는 것이다.
# (12) pairgrid()
grid = sns.PairGrid(new_df_titanic[['survived','age','fare']])
grid.map_diag(sns.histplot)
grid.map_lower(sns.kdeplot)
grid.map_upper(sns.scatterplot)
plt.show()

# (12) pairgrid()
grid = sns.PairGrid(new_df_titanic[['survived','age','fare','sex']],hue='sex')
grid.map_diag(sns.histplot)
grid.map_lower(sns.kdeplot)
grid.map_upper(sns.scatterplot)
plt.show()
