2024.01.03
데이터 핸들링 실습
지난번에 이어 다른 데이터 셋으로 연습
캐글의 titanic 데이터 활용
https://www.kaggle.com/competitions
Kaggle Competitions
www.kaggle.com
- 패키지 설치 및 데이터 불러오기
!pip install --upgrade pandas
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
path = '/content/drive/MyDrive/titanic_train.csv'
data = pd.read_csv(path,sep=',', index_col = 'PassengerId')
data.head()
기본적인 데이터 전처리는 지난 번과 비슷하여 생략
- 그래프 그리기
# 성별 인원 수 확인
data["Sex"].value_counts() # 일반 수치만 확인
data["Sex"].value_counts().plot(kind='bar', title= 'F/M Counts', color=['g','b'])
# 추가) 값에 따라 특정 색 지정
color_dict = { "male":"r", "female":"g"}
data["Sex"].value_counts().plot(kind="bar",
title="F/M Counts",
color=data["Sex"].replace(color_dict))
- crosstab을 활용하여 정보 확인
# 선실 등급에 따른 남성/여성 수 구하기
# 기본
pd.crosstab(data["Pclass"], data["Sex"])
# 색 지정
pd.crosstab(data["Pclass"], data["Sex"]).style.background_gradient(cmap="Greys")
cmap 파라미터에 들어갈 색 정보는 하단 사이트 참조
Colormap reference — Matplotlib 3.9.1 documentation
Colormap reference Reference for colormaps included with Matplotlib. A reversed version of each of these colormaps is available by appending _r to the name, as shown in Reversed colormaps. See Choosing Colormaps in Matplotlib for an in-depth discussion abo
matplotlib.org
- 데이터 시각화 (seaborn 패키지)
# 객실 등급에 따른 요금 분포
sns.boxplot( data= data, x="Pclass", y="Fare")
# 이상치 처리를 위해 상위 95% 정보만 시각화
sns.boxplot( data= data[ data["Fare"] < data["Fare"].quantile(0.95)],
x="Pclass", y="Fare")
# 객실 등급에 따른 생존률 시각화
data.groupby(by=["Pclass"]).agg({"Survived":"mean"}).plot(kind='bar')
data.groupby(by=["Pclass"])["Survived"].mean() # 간단한 표현식
# 객실별 승객 수와 생존율 그래프 한 번에 그리기
fig, axes = plt.subplots( nrows=1, ncols=2)
# 왼쪽 그림 설정: pandas + plot
data.groupby(by=["Pclass"]).agg({"Survived":"mean"}).plot(kind='bar',color='r',ax=axes[0])
axes[0].set_ylabel("Pclass counts")
# 오른쪽 그림 설정: seaborn + countplot
sns.countplot(data=data, x="Pclass",hue="Survived",ax=axes[1])
# 서로 다른 패키지 함수를 하나의 판에 집어 넣을 수 있음
axes[1].set_title("Pclass vs. Survived")
fig.tight_layout()
'ASAC 빅데이터전문가과정 > Python' 카테고리의 다른 글
ASAC 27일차 _ 재귀함수, 퀵 정렬 (0) | 2024.08.13 |
---|---|
ASAC 25-26일차 _ 태블로 강의 (0) | 2024.08.13 |
ASAC 23일차 _ 데이터 핸들링(1) (0) | 2024.08.12 |
ASAC 22일차 _ Matplotlib (0) | 2024.08.08 |
ASAC 20일차 _ WebCrawling(4), Pandas(5) (0) | 2024.08.05 |