먼저 Pandas를 사용하여 타이타닉 데이터를 불러오고 기본적인 정보를 확인합니다.
예시 코드:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 데이터 불러오기 (일반적으로 CSV 파일 사용)
# 여기서는 예시로 DataFrame을 직접 생성하거나, 웹에서 불러옵니다.
# 실제 사용 시: df = pd.read_csv('titanic.csv')
# Kaggle의 타이타닉 데이터셋 URL
url = 'https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv'
try:
df = pd.read_csv(url)
except Exception as e:
print(f"Error loading data: {e}")
# 대체 데이터 (오류 발생 시)
data = {'Survived': [0, 1, 1, 1, 0, 0, 0, 0, 1, 1],
'Pclass': [3, 1, 3, 1, 3, 3, 1, 3, 3, 2],
'Name': ['Braund, Mr. Owen Harris', 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)',
'Heikkinen, Miss. Laina', 'Futrelle, Mrs. Jacques Heath (Lily May Peel)',
'Allen, Mr. William Henry', 'Moran, Mr. James', 'McCarthy, Mr. Timothy J',
'Palsson, Master. Gosta Leonard', 'Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)',
'Nasser, Mrs. Nicholas (Adele Achem)'],
'Sex': ['male', 'female', 'female', 'female', 'male', 'male', 'male', 'male', 'female', 'female'],
'Age': [22, 38, 26, 35, 35, np.nan, 54, 2, 27, 14],
'SibSp': [1, 1, 0, 1, 0, 0, 0, 3, 0, 1],
'Parch': [0, 0, 0, 0, 0, 0, 0, 1, 2, 0],
'Ticket': ['A/5 21171', 'PC 17599', 'STON/O2. 3101282', '113803', '373450', '330877', '17463', '349909', '347742', '237736'],
'Fare': [7.25, 71.2833, 7.925, 53.1, 8.05, 8.4583, 51.8625, 21.075, 11.1333, 30.0708],
'Cabin': [np.nan, 'C85', np.nan, 'C123', np.nan, np.nan, 'E46', np.nan, np.nan, np.nan],
'Embarked': ['S', 'C', 'S', 'S', 'S', 'Q', 'S', 'S', 'S', 'C']}
df = pd.DataFrame(data)
print("--- 데이터 샘플 (처음 5개 행) ---")
print(df.head())
print("\n--- 데이터 정보 ---")
df.info()
print("\n--- 기술 통계 ---")
print(df.describe())
print("\n--- 결측치 확인 ---")
print(df.isnull().sum())
# 간단한 전처리: Age 결측치를 평균으로 채우기
df['Age'].fillna(df['Age'].mean(), inplace=True)
# Embarked 결측치를 최빈값으로 채우기 (데이터가 있다면)
if 'Embarked' in df.columns and df['Embarked'].isnull().any():
df['Embarked'].fillna(df['Embarked'].mode()[0], inplace=True)
print("\n--- 전처리 후 결측치 확인 ---")
print(df.isnull().sum())
예상 결과:
--- 데이터 샘플 (처음 5개 행) ---
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
--- 데이터 정보 ---
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890 (실제 데이터셋의 경우, 예제는 10개)
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Survived 891 non-null int64
1 Pclass 891 non-null int64
2 Name 891 non-null object
3 Sex 891 non-null object
4 Age 714 non-null float64
5 SibSp 891 non-null int64
6 Parch 891 non-null int64
7 Ticket 891 non-null object
8 Fare 891 non-null float64
9 Cabin 204 non-null object
10 Embarked 889 non-null object
dtypes: float64(2), int64(4), object(6) (실제 데이터셋 기준, 예제는 다를 수 있음)
memory usage: 83.7+ KB
--- 기술 통계 ---
Survived Pclass Age SibSp Parch Fare
count 891.000000 891.000000 714.000000 891.000000 891.000000 891.000000
mean 0.383838 2.308642 29.699118 0.523008 0.381594 32.204208
std 0.486592 0.836071 14.526497 1.102743 0.806057 49.693429
min 0.000000 1.000000 0.420000 0.000000 0.000000 0.000000
25% 0.000000 2.000000 20.125000 0.000000 0.000000 7.910400
50% 0.000000 3.000000 28.000000 0.000000 0.000000 14.454200
75% 1.000000 3.000000 38.000000 1.000000 0.000000 31.000000
max 1.000000 3.000000 80.000000 8.000000 6.000000 512.329200 (실제 데이터셋 기준)
--- 결측치 확인 ---
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64 (실제 데이터셋 기준)
--- 전처리 후 결측치 확인 ---
Survived 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 0
dtype: int64 (실제 데이터셋 기준, Cabin은 여전히 많음)