<안내>
필자도 배우는 입장이라 틀린점, 잘못된 점이 있을 수 있습니다.
그러니 지적, 피드백 환영합니다.
4. Exploratory Data Analysis¶
탐색적 데이터 분석을 통해 데이터를 통달해봅시다. with Titanic Data
- 라이브러리 준비
- 분석의 목적과 변수 확인
- 데이터 전체적으로 살펴보기
- 데이터의 개별 속성 파악하기
0. 라이브러리 준비¶
In [1]:
## 라이브러리 불러오기
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
In [4]:
## 동일경로에 "train.csv"가 있다면:
## 데이터 불러오기
titanic_df = pd.read_csv("./train.csv")
1. 분석의 목적과 변수 확인¶
- 타이타닉 호에서 생존한 생존자들은 어떤 사람들일까?
In [5]:
## 상위 5개 데이터 확인하기
titanic_df.head(5)
Out[5]:
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
In [6]:
## 각 Column의 데이터 타입확인하기
titanic_df.dtypes
Out[6]:
PassengerId int64
Survived int64
Pclass int64
Name object
Sex object
Age float64
SibSp int64
Parch int64
Ticket object
Fare float64
Cabin object
Embarked object
dtype: object
2. 데이터 전체적으로 살펴보기¶
In [8]:
## 데이터 전체 정보를 얻는 함수 : .describe()
titanic_df.describe() # 수치형 데이터에 대한 요약만을 제공!
Out[8]:
PassengerId | Survived | Pclass | Age | SibSp | Parch | Fare | |
---|---|---|---|---|---|---|---|
count | 891.000000 | 891.000000 | 891.000000 | 714.000000 | 891.000000 | 891.000000 | 891.000000 |
mean | 446.000000 | 0.383838 | 2.308642 | 29.699118 | 0.523008 | 0.381594 | 32.204208 |
std | 257.353842 | 0.486592 | 0.836071 | 14.526497 | 1.102743 | 0.806057 | 49.693429 |
min | 1.000000 | 0.000000 | 1.000000 | 0.420000 | 0.000000 | 0.000000 | 0.000000 |
25% | 223.500000 | 0.000000 | 2.000000 | 20.125000 | 0.000000 | 0.000000 | 7.910400 |
50% | 446.000000 | 0.000000 | 3.000000 | 28.000000 | 0.000000 | 0.000000 | 14.454200 |
75% | 668.500000 | 1.000000 | 3.000000 | 38.000000 | 1.000000 | 0.000000 | 31.000000 |
max | 891.000000 | 1.000000 | 3.000000 | 80.000000 | 8.000000 | 6.000000 | 512.329200 |
In [10]:
## 상관계수 확인!
titanic_df.corr()
# Correalation is NOT Causation
# 상관성 : A UP, B UP, ...
# 인과성 : A -> B
# 음의 상관 : 적을수록 많아지는 것
Out[10]:
PassengerId | Survived | Pclass | Age | SibSp | Parch | Fare | |
---|---|---|---|---|---|---|---|
PassengerId | 1.000000 | -0.005007 | -0.035144 | 0.036847 | -0.057527 | -0.001652 | 0.012658 |
Survived | -0.005007 | 1.000000 | -0.338481 | -0.077221 | -0.035322 | 0.081629 | 0.257307 |
Pclass | -0.035144 | -0.338481 | 1.000000 | -0.369226 | 0.083081 | 0.018443 | -0.549500 |
Age | 0.036847 | -0.077221 | -0.369226 | 1.000000 | -0.308247 | -0.189119 | 0.096067 |
SibSp | -0.057527 | -0.035322 | 0.083081 | -0.308247 | 1.000000 | 0.414838 | 0.159651 |
Parch | -0.001652 | 0.081629 | 0.018443 | -0.189119 | 0.414838 | 1.000000 | 0.216225 |
Fare | 0.012658 | 0.257307 | -0.549500 | 0.096067 | 0.159651 | 0.216225 | 1.000000 |
In [11]:
## 결측치 확인
titanic_df.isnull().sum()
# Age, Cabin, Embarked에서 결측치 발견!
Out[11]:
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64
In [15]:
## 생존자, 사망자의 수는?
titanic_df['Survived'].sum() # 1이 생존자니까 sum은 모든 생존자 수가 나옴
titanic_df['Survived'].value_counts() # 생존자와 사망자의 수를 볼 수 있음
Out[15]:
0 549
1 342
Name: Survived, dtype: int64
In [18]:
## 생존자 수와 사망자 수를 Barplot으로 그려보기 sns.countplot()
sns.countplot(x = 'Survived', data = titanic_df)
plt.show()
II. Pclass¶
In [25]:
# Pclass 에 따른 인원 파악
titanic_df[['Pclass', 'Survived']].groupby(['Pclass']).count()
# Pclass마다 몇명의 승객이있는지
Out[25]:
Survived | |
---|---|
Pclass | |
1 | 216 |
2 | 184 |
3 | 491 |
In [26]:
# 생존자 인원?
titanic_df[['Pclass', 'Survived']].groupby(['Pclass']).sum()
# survived가 1인 개수
Out[26]:
Survived | |
---|---|
Pclass | |
1 | 136 |
2 | 87 |
3 | 119 |
In [28]:
# 생존 비율?
titanic_df[['Pclass', 'Survived']].groupby(['Pclass']).mean()
# count에 대해서 sum 을 count 로 나눈다 라는 말
# 그말은 전체 인원에 대해 얼만큼의 비율이 살아남았나 라는 의미
Out[28]:
Survived | |
---|---|
Pclass | |
1 | 0.629630 |
2 | 0.472826 |
3 | 0.242363 |
In [32]:
# 히트맵 활용
sns.heatmap(titanic_df[['Pclass', 'Survived']].groupby(['Pclass']).mean())
plt.show()
III. Sex¶
In [33]:
titanic_df[['Sex', 'Survived']]
Out[33]:
Sex | Survived | |
---|---|---|
0 | male | 0 |
1 | female | 1 |
2 | female | 1 |
3 | female | 1 |
4 | male | 0 |
... | ... | ... |
886 | male | 0 |
887 | female | 1 |
888 | female | 0 |
889 | male | 1 |
890 | male | 0 |
891 rows × 2 columns
In [36]:
titanic_df.groupby(['Survived','Sex'])['Survived'].count()
Out[36]:
Survived Sex
0 female 81
male 468
1 female 233
male 109
Name: Survived, dtype: int64
In [40]:
# sns.catplot
sns.catplot(x= 'Sex',col = 'Survived' ,kind = 'count', data = titanic_df)
plt.show()
IV. Age¶
Remind : 결측치 존재
In [41]:
titanic_df.describe()['Age']
Out[41]:
count 714.000000
mean 29.699118
std 14.526497
min 0.420000
25% 20.125000
50% 28.000000
75% 38.000000
max 80.000000
Name: Age, dtype: float64
In [45]:
## Survived 1, 0 과 Age으 경향성
fig, ax = plt.subplots(1,1,figsize=(10,5))
sns.kdeplot(x =titanic_df[titanic_df.Survived ==1]['Age'] , ax = ax )
sns.kdeplot(x =titanic_df[titanic_df.Survived ==0]['Age'] , ax = ax )
plt.legend(['Survived','Dead'])
plt.show()
Appendix I . Sex + Pclass vs Survived¶
In [48]:
sns.catplot (x = 'Pclass', y = 'Survived',hue = 'Sex', kind = 'point', data = titanic_df)
plt.show()
Appendix II. Age + Pclass¶
In [52]:
## Age graph with pclass
titanic_df['Age'][titanic_df.Pclass == 1].plot(kind = 'kde')
titanic_df['Age'][titanic_df.Pclass == 2].plot(kind = 'kde')
titanic_df['Age'][titanic_df.Pclass == 3].plot(kind = 'kde')
plt.legend(['1st class', '2nd class', '3rd class'])
Out[52]:
<matplotlib.legend.Legend at 0x15f31774340>
Mission : It's Your Turn!¶
1. 본문에서 언급된 Feature를 제외하고 유의미한 Feature를 1개 이상 찾아봅시다.¶
- with Survived
- Hint : Fare? Sibsp? Parch?
2. Kaggle에서 Dataset을 찾고, 이 Dataset에서 유의미한 Feature를 3개 이상 찾고 이를 시각화해봅시다.¶
함께 보면 좋은 라이브러리 document
무대뽀로 하기 힘들다면? 다음 Hint와 함께 시도해봅시다:¶
- 데이터를 톺아봅시다.
- 각 데이터는 어떤 자료형을 가지고 있나요?
- 데이터에 결측치는 없나요? -> 있다면 이를 어떻게 메꿔줄까요?
- 데이터의 자료형을 바꿔줄 필요가 있나요? -> 범주형의 One-hot encoding
- 데이터에 대한 가설을 세워봅시다.
- 가설은 개인의 경험에 의해서 도출되어도 상관이 없습니다.
- 가설은 명확할 수록 좋습니다 ex) Titanic Data에서 Survival 여부와 성별에는 상관관계가 있다!
- 가설을 검증하기 위한 증거를 찾아봅시다.
- 이 증거는 한 눈에 보이지 않을 수 있습니다. 우리가 다룬 여러 Technique를 써줘야합니다.
.groupby()
를 통해서 그룹화된 정보에 통계량을 도입하면 어떨까요?.merge()
를 통해서 두개 이상의 dataFrame을 합치면 어떨까요?- 시각화를 통해 일목요연하게 보여주면 더욱 좋겠죠?
In [ ]:
flask를 이용한 API 구축 과제가 생각보다 잘 되지가 않는다.
공부시간동안 머리를 두들겨봐도 적당한 해답을 찾을 수 없었다... 이런..
내일 할 공부
목 금요일 분 EDA강의 듣기 및 질문할 내용 정리해놓기
'TIL > [겨울방학 부트캠프]TIL' 카테고리의 다른 글
TIL 12일차 (22.01.17) (0) | 2022.01.18 |
---|---|
TIL 11일차 (22.01.16) (0) | 2022.01.17 |
TIL 9일차 (22.01.13) (0) | 2022.01.14 |
TIL 8일차 (22.01.12) (0) | 2022.01.13 |
TIL 7일차 (22.01.11) (0) | 2022.01.12 |