WeniVooks

검색

Right Now, Polars

타이타닉 데이터 분석

1. 데이터 불러오기

# seaborn의 titanic 데이터셋 로드
titanic_df = pl.from_pandas(sns.load_dataset('titanic'))
titanic_df
# seaborn의 titanic 데이터셋 로드
titanic_df = pl.from_pandas(sns.load_dataset('titanic'))
titanic_df

2. 데이터 정보 확인

print("데이터 기본 정보:")
print(titanic_df.glimpse())
print(titanic_df.describe())
print("데이터 기본 정보:")
print(titanic_df.glimpse())
print(titanic_df.describe())
데이터 기본 정보:
Rows: 891
Columns: 15
$ survived     <i64> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1
$ pclass       <i64> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2
$ sex          <str> 'male', 'female', 'female', 'female', 'male', 'male', 'male', 'male', 'female', 'female'
$ age          <f64> 22.0, 38.0, 26.0, 35.0, 35.0, None, 54.0, 2.0, 27.0, 14.0
$ sibsp        <i64> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1
$ parch        <i64> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0
$ fare         <f64> 7.25, 71.2833, 7.925, 53.1, 8.05, 8.4583, 51.8625, 21.075, 11.1333, 30.0708
$ embarked     <str> 'S', 'C', 'S', 'S', 'S', 'Q', 'S', 'S', 'S', 'C'
$ class        <cat> Third, First, Third, First, Third, Third, First, Third, Third, Second
$ who          <str> 'man', 'woman', 'woman', 'woman', 'man', 'man', 'man', 'child', 'woman', 'child'
$ adult_male  <bool> True, False, False, False, True, True, True, False, False, False
$ deck         <cat> None, C, None, C, None, None, E, None, None, None
$ embark_town  <str> 'Southampton', 'Cherbourg', 'Southampton', 'Southampton', 'Southampton', 'Queenstown', 'Southampton', 'Southampton', 'Southampton', 'Cherbourg'
$ alive        <str> 'no', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'yes'
$ alone       <bool> False, False, True, False, True, True, True, False, False, False

None
shape: (9, 16)
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬────────┐
│ sta ┆ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ far ┆ emb ┆ cla ┆ who ┆ adu ┆ dec ┆ emb ┆ ali ┆ alone  │
│ tis ┆ viv ┆ ass ┆ --- ┆ --- ┆ sp  ┆ ch  ┆ e   ┆ ark ┆ ss  ┆ --- ┆ lt_ ┆ k   ┆ ark ┆ ve  ┆ ---    │
│ tic ┆ ed  ┆ --- ┆ str ┆ f64 ┆ --- ┆ --- ┆ --- ┆ ed  ┆ --- ┆ str ┆ mal ┆ --- ┆ _to ┆ --- ┆ f64    │
│ --- ┆ --- ┆ f64 ┆     ┆     ┆ f64 ┆ f64 ┆ f64 ┆ --- ┆ str ┆     ┆ e   ┆ str ┆ wn  ┆ str ┆        │
│ str ┆ f64 ┆     ┆     ┆     ┆     ┆     ┆     ┆ str ┆     ┆     ┆ --- ┆     ┆ --- ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ f64 ┆     ┆ str ┆     ┆        │
╞═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪════════╡
│ cou ┆ 891 ┆ 891 ┆ 891 ┆ 714 ┆ 891 ┆ 891 ┆ 891 ┆ 889 ┆ 891 ┆ 891 ┆ 891 ┆ 203 ┆ 889 ┆ 891 ┆ 891.0  │
│ nt  ┆ .0  ┆ .0  ┆     ┆ .0  ┆ .0  ┆ .0  ┆ .0  ┆     ┆     ┆     ┆ .0  ┆     ┆     ┆     ┆        │
│ nul ┆ 0.0 ┆ 0.0 ┆ 0   ┆ 177 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 2   ┆ 0   ┆ 0   ┆ 0.0 ┆ 688 ┆ 2   ┆ 0   ┆ 0.0    │
│ l_c ┆     ┆     ┆     ┆ .0  ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ oun ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ t   ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ mea ┆ 0.3 ┆ 2.3 ┆ nul ┆ 29. ┆ 0.5 ┆ 0.3 ┆ 32. ┆ nul ┆ nul ┆ nul ┆ 0.6 ┆ nul ┆ nul ┆ nul ┆ 0.6026 │
│ n   ┆ 838 ┆ 086 ┆ l   ┆ 699 ┆ 230 ┆ 815 ┆ 204 ┆ l   ┆ l   ┆ l   ┆ 026 ┆ l   ┆ l   ┆ l   ┆ 94     │
│     ┆ 38  ┆ 42  ┆     ┆ 118 ┆ 08  ┆ 94  ┆ 208 ┆     ┆     ┆     ┆ 94  ┆     ┆     ┆     ┆        │
│ std ┆ 0.4 ┆ 0.8 ┆ nul ┆ 14. ┆ 1.1 ┆ 0.8 ┆ 49. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆ 865 ┆ 360 ┆ l   ┆ 526 ┆ 027 ┆ 060 ┆ 693 ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│     ┆ 92  ┆ 71  ┆     ┆ 497 ┆ 43  ┆ 57  ┆ 429 ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ min ┆ 0.0 ┆ 1.0 ┆ fem ┆ 0.4 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ C   ┆ nul ┆ chi ┆ 0.0 ┆ nul ┆ Che ┆ no  ┆ 0.0    │
│     ┆     ┆     ┆ ale ┆ 2   ┆     ┆     ┆     ┆     ┆ l   ┆ ld  ┆     ┆ l   ┆ rbo ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ urg ┆     ┆        │
│ 25% ┆ 0.0 ┆ 2.0 ┆ nul ┆ 20. ┆ 0.0 ┆ 0.0 ┆ 7.9 ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 25  ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│ 50% ┆ 0.0 ┆ 3.0 ┆ nul ┆ 28. ┆ 0.0 ┆ 0.0 ┆ 14. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 454 ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆ 2   ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ 75% ┆ 1.0 ┆ 3.0 ┆ nul ┆ 38. ┆ 1.0 ┆ 0.0 ┆ 31. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 0   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│ max ┆ 1.0 ┆ 3.0 ┆ mal ┆ 80. ┆ 8.0 ┆ 6.0 ┆ 512 ┆ S   ┆ nul ┆ wom ┆ 1.0 ┆ nul ┆ Sou ┆ yes ┆ 1.0    │
│     ┆     ┆     ┆ e   ┆ 0   ┆     ┆     ┆ .32 ┆     ┆ l   ┆ an  ┆     ┆ l   ┆ tha ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆ 92  ┆     ┆     ┆     ┆     ┆     ┆ mpt ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ on  ┆     ┆        │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴────────┘
데이터 기본 정보:
Rows: 891
Columns: 15
$ survived     <i64> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1
$ pclass       <i64> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2
$ sex          <str> 'male', 'female', 'female', 'female', 'male', 'male', 'male', 'male', 'female', 'female'
$ age          <f64> 22.0, 38.0, 26.0, 35.0, 35.0, None, 54.0, 2.0, 27.0, 14.0
$ sibsp        <i64> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1
$ parch        <i64> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0
$ fare         <f64> 7.25, 71.2833, 7.925, 53.1, 8.05, 8.4583, 51.8625, 21.075, 11.1333, 30.0708
$ embarked     <str> 'S', 'C', 'S', 'S', 'S', 'Q', 'S', 'S', 'S', 'C'
$ class        <cat> Third, First, Third, First, Third, Third, First, Third, Third, Second
$ who          <str> 'man', 'woman', 'woman', 'woman', 'man', 'man', 'man', 'child', 'woman', 'child'
$ adult_male  <bool> True, False, False, False, True, True, True, False, False, False
$ deck         <cat> None, C, None, C, None, None, E, None, None, None
$ embark_town  <str> 'Southampton', 'Cherbourg', 'Southampton', 'Southampton', 'Southampton', 'Queenstown', 'Southampton', 'Southampton', 'Southampton', 'Cherbourg'
$ alive        <str> 'no', 'yes', 'yes', 'yes', 'no', 'no', 'no', 'no', 'yes', 'yes'
$ alone       <bool> False, False, True, False, True, True, True, False, False, False

None
shape: (9, 16)
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬────────┐
│ sta ┆ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ far ┆ emb ┆ cla ┆ who ┆ adu ┆ dec ┆ emb ┆ ali ┆ alone  │
│ tis ┆ viv ┆ ass ┆ --- ┆ --- ┆ sp  ┆ ch  ┆ e   ┆ ark ┆ ss  ┆ --- ┆ lt_ ┆ k   ┆ ark ┆ ve  ┆ ---    │
│ tic ┆ ed  ┆ --- ┆ str ┆ f64 ┆ --- ┆ --- ┆ --- ┆ ed  ┆ --- ┆ str ┆ mal ┆ --- ┆ _to ┆ --- ┆ f64    │
│ --- ┆ --- ┆ f64 ┆     ┆     ┆ f64 ┆ f64 ┆ f64 ┆ --- ┆ str ┆     ┆ e   ┆ str ┆ wn  ┆ str ┆        │
│ str ┆ f64 ┆     ┆     ┆     ┆     ┆     ┆     ┆ str ┆     ┆     ┆ --- ┆     ┆ --- ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ f64 ┆     ┆ str ┆     ┆        │
╞═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪════════╡
│ cou ┆ 891 ┆ 891 ┆ 891 ┆ 714 ┆ 891 ┆ 891 ┆ 891 ┆ 889 ┆ 891 ┆ 891 ┆ 891 ┆ 203 ┆ 889 ┆ 891 ┆ 891.0  │
│ nt  ┆ .0  ┆ .0  ┆     ┆ .0  ┆ .0  ┆ .0  ┆ .0  ┆     ┆     ┆     ┆ .0  ┆     ┆     ┆     ┆        │
│ nul ┆ 0.0 ┆ 0.0 ┆ 0   ┆ 177 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 2   ┆ 0   ┆ 0   ┆ 0.0 ┆ 688 ┆ 2   ┆ 0   ┆ 0.0    │
│ l_c ┆     ┆     ┆     ┆ .0  ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ oun ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ t   ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ mea ┆ 0.3 ┆ 2.3 ┆ nul ┆ 29. ┆ 0.5 ┆ 0.3 ┆ 32. ┆ nul ┆ nul ┆ nul ┆ 0.6 ┆ nul ┆ nul ┆ nul ┆ 0.6026 │
│ n   ┆ 838 ┆ 086 ┆ l   ┆ 699 ┆ 230 ┆ 815 ┆ 204 ┆ l   ┆ l   ┆ l   ┆ 026 ┆ l   ┆ l   ┆ l   ┆ 94     │
│     ┆ 38  ┆ 42  ┆     ┆ 118 ┆ 08  ┆ 94  ┆ 208 ┆     ┆     ┆     ┆ 94  ┆     ┆     ┆     ┆        │
│ std ┆ 0.4 ┆ 0.8 ┆ nul ┆ 14. ┆ 1.1 ┆ 0.8 ┆ 49. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆ 865 ┆ 360 ┆ l   ┆ 526 ┆ 027 ┆ 060 ┆ 693 ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│     ┆ 92  ┆ 71  ┆     ┆ 497 ┆ 43  ┆ 57  ┆ 429 ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ min ┆ 0.0 ┆ 1.0 ┆ fem ┆ 0.4 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ C   ┆ nul ┆ chi ┆ 0.0 ┆ nul ┆ Che ┆ no  ┆ 0.0    │
│     ┆     ┆     ┆ ale ┆ 2   ┆     ┆     ┆     ┆     ┆ l   ┆ ld  ┆     ┆ l   ┆ rbo ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ urg ┆     ┆        │
│ 25% ┆ 0.0 ┆ 2.0 ┆ nul ┆ 20. ┆ 0.0 ┆ 0.0 ┆ 7.9 ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 25  ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│ 50% ┆ 0.0 ┆ 3.0 ┆ nul ┆ 28. ┆ 0.0 ┆ 0.0 ┆ 14. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 454 ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆ 2   ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆        │
│ 75% ┆ 1.0 ┆ 3.0 ┆ nul ┆ 38. ┆ 1.0 ┆ 0.0 ┆ 31. ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ nul ┆ null   │
│     ┆     ┆     ┆ l   ┆ 0   ┆     ┆     ┆ 0   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆ l   ┆        │
│ max ┆ 1.0 ┆ 3.0 ┆ mal ┆ 80. ┆ 8.0 ┆ 6.0 ┆ 512 ┆ S   ┆ nul ┆ wom ┆ 1.0 ┆ nul ┆ Sou ┆ yes ┆ 1.0    │
│     ┆     ┆     ┆ e   ┆ 0   ┆     ┆     ┆ .32 ┆     ┆ l   ┆ an  ┆     ┆ l   ┆ tha ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆ 92  ┆     ┆     ┆     ┆     ┆     ┆ mpt ┆     ┆        │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ on  ┆     ┆        │
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴────────┘
print(titanic_df.shape)
print(titanic_df.shape)
(891, 15)
(891, 15)

3. 데이터 전처리

3.1 결측값 확인
print("결측치 개수:")
print(titanic_df.null_count())
print("결측치 개수:")
print(titanic_df.null_count())
결측치 개수:
shape: (1, 15)
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬──────┬─────────┬───────┬───────┐
│ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ far ┆ emb ┆ cla ┆ who ┆ adu ┆ deck ┆ embark_ ┆ alive ┆ alone │
│ viv ┆ ass ┆ ------ ┆ sp  ┆ ch  ┆ e   ┆ ark ┆ ss  ┆ --- ┆ lt_ ┆ ---  ┆ town    ┆ ------
│ ed  ┆ --- ┆ u32 ┆ u32 ┆ --------- ┆ ed  ┆ --- ┆ u32 ┆ mal ┆ u32  ┆ ---     ┆ u32   ┆ u32   │
--- ┆ u32 ┆     ┆     ┆ u32 ┆ u32 ┆ u32 ┆ --- ┆ u32 ┆     ┆ e   ┆      ┆ u32     ┆       ┆       │
│ u32 ┆     ┆     ┆     ┆     ┆     ┆     ┆ u32 ┆     ┆     ┆ --- ┆      ┆         ┆       ┆       │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ u32 ┆      ┆         ┆       ┆       │
╞═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪══════╪═════════╪═══════╪═══════╡
0001770002000688200
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴──────┴─────────┴───────┴───────┘
결측치 개수:
shape: (1, 15)
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬──────┬─────────┬───────┬───────┐
│ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ far ┆ emb ┆ cla ┆ who ┆ adu ┆ deck ┆ embark_ ┆ alive ┆ alone │
│ viv ┆ ass ┆ ------ ┆ sp  ┆ ch  ┆ e   ┆ ark ┆ ss  ┆ --- ┆ lt_ ┆ ---  ┆ town    ┆ ------
│ ed  ┆ --- ┆ u32 ┆ u32 ┆ --------- ┆ ed  ┆ --- ┆ u32 ┆ mal ┆ u32  ┆ ---     ┆ u32   ┆ u32   │
--- ┆ u32 ┆     ┆     ┆ u32 ┆ u32 ┆ u32 ┆ --- ┆ u32 ┆     ┆ e   ┆      ┆ u32     ┆       ┆       │
│ u32 ┆     ┆     ┆     ┆     ┆     ┆     ┆ u32 ┆     ┆     ┆ --- ┆      ┆         ┆       ┆       │
│     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆     ┆ u32 ┆      ┆         ┆       ┆       │
╞═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╪══════╪═════════╪═══════╪═══════╡
0001770002000688200
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴──────┴─────────┴───────┴───────┘
3.2 데이터 삭제
titanic_df = titanic_df.drop(['deck'])
titanic_df
titanic_df = titanic_df.drop(['deck'])
titanic_df
3.3 결측치 채우기
titanic_df = titanic_df.with_columns((pl.col('age').fill_null(strategy='mean')).alias('age'))
titanic_df
titanic_df = titanic_df.with_columns((pl.col('age').fill_null(strategy='mean')).alias('age'))
titanic_df
titanic_df = titanic_df.with_columns((pl.col('embarked').fill_null(titanic_df['embarked'].mode()[0])).alias('embarked'))
titanic_df = titanic_df.with_columns((pl.col('embark_town').fill_null(titanic_df['embark_town'].mode()[0])).alias('embark_town'))
titanic_df
titanic_df = titanic_df.with_columns((pl.col('embarked').fill_null(titanic_df['embarked'].mode()[0])).alias('embarked'))
titanic_df = titanic_df.with_columns((pl.col('embark_town').fill_null(titanic_df['embark_town'].mode()[0])).alias('embark_town'))
titanic_df
print("결측치 개수:")
print(titanic_df.null_count())
print("결측치 개수:")
print(titanic_df.null_count())
결측치 개수:
shape: (1, 14)
┌─────┬─────┬─────┬─────┬─────┬─────┬──────┬────────┬───────┬─────┬────────┬───────┬───────┬───────┐
│ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ fare ┆ embark ┆ class ┆ who ┆ adult_ ┆ embar ┆ alive ┆ alone │
│ viv ┆ ass ┆ --- ┆ --- ┆ sp  ┆ ch  ┆ ---  ┆ ed     ┆ ---   ┆ --- ┆ male   ┆ k_tow ┆ ---   ┆ ---   │
│ ed  ┆ --- ┆ u32 ┆ u32 ┆ --- ┆ --- ┆ u32  ┆ ---    ┆ u32   ┆ u32 ┆ ---    ┆ n     ┆ u32   ┆ u32   │
│ --- ┆ u32 ┆     ┆     ┆ u32 ┆ u32 ┆      ┆ u32    ┆       ┆     ┆ u32    ┆ ---   ┆       ┆       │
│ u32 ┆     ┆     ┆     ┆     ┆     ┆      ┆        ┆       ┆     ┆        ┆ u32   ┆       ┆       │
╞═════╪═════╪═════╪═════╪═════╪═════╪══════╪════════╪═══════╪═════╪════════╪═══════╪═══════╪═══════╡
│ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0    ┆ 0      ┆ 0     ┆ 0   ┆ 0      ┆ 0     ┆ 0     ┆ 0     │
└─────┴─────┴─────┴─────┴─────┴─────┴──────┴────────┴───────┴─────┴────────┴───────┴───────┴───────┘
결측치 개수:
shape: (1, 14)
┌─────┬─────┬─────┬─────┬─────┬─────┬──────┬────────┬───────┬─────┬────────┬───────┬───────┬───────┐
│ sur ┆ pcl ┆ sex ┆ age ┆ sib ┆ par ┆ fare ┆ embark ┆ class ┆ who ┆ adult_ ┆ embar ┆ alive ┆ alone │
│ viv ┆ ass ┆ --- ┆ --- ┆ sp  ┆ ch  ┆ ---  ┆ ed     ┆ ---   ┆ --- ┆ male   ┆ k_tow ┆ ---   ┆ ---   │
│ ed  ┆ --- ┆ u32 ┆ u32 ┆ --- ┆ --- ┆ u32  ┆ ---    ┆ u32   ┆ u32 ┆ ---    ┆ n     ┆ u32   ┆ u32   │
│ --- ┆ u32 ┆     ┆     ┆ u32 ┆ u32 ┆      ┆ u32    ┆       ┆     ┆ u32    ┆ ---   ┆       ┆       │
│ u32 ┆     ┆     ┆     ┆     ┆     ┆      ┆        ┆       ┆     ┆        ┆ u32   ┆       ┆       │
╞═════╪═════╪═════╪═════╪═════╪═════╪══════╪════════╪═══════╪═════╪════════╪═══════╪═══════╪═══════╡
│ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0   ┆ 0    ┆ 0      ┆ 0     ┆ 0   ┆ 0      ┆ 0     ┆ 0     ┆ 0     │
└─────┴─────┴─────┴─────┴─────┴─────┴──────┴────────┴───────┴─────┴────────┴───────┴───────┴───────┘

4. 생존율 분석

survival_analysis = (
    titanic_df.group_by('class')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('전체승객수')
    ])
    .sort('생존율', descending=True)
)
print("객실 등급별 생존율:")
print(survival_analysis)
survival_analysis = (
    titanic_df.group_by('class')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('전체승객수')
    ])
    .sort('생존율', descending=True)
)
print("객실 등급별 생존율:")
print(survival_analysis)
객실 등급별 생존율:
shape: (3, 4)
┌────────┬───────────┬──────────┬────────────┐
│ class  ┆ 생존율    ┆ 생존자수 ┆ 전체승객수 │
│ ---    ┆ ---       ┆ ---      ┆ ---        │
│ cat    ┆ f64       ┆ i64      ┆ u32        │
╞════════╪═══════════╪══════════╪════════════╡
│ First  ┆ 62.962963 ┆ 136      ┆ 216        │
│ Second ┆ 47.282609 ┆ 87       ┆ 184        │
│ Third  ┆ 24.236253 ┆ 119      ┆ 491        │
└────────┴───────────┴──────────┴────────────┘
객실 등급별 생존율:
shape: (3, 4)
┌────────┬───────────┬──────────┬────────────┐
│ class  ┆ 생존율    ┆ 생존자수 ┆ 전체승객수 │
│ ---    ┆ ---       ┆ ---      ┆ ---        │
│ cat    ┆ f64       ┆ i64      ┆ u32        │
╞════════╪═══════════╪══════════╪════════════╡
│ First  ┆ 62.962963 ┆ 136      ┆ 216        │
│ Second ┆ 47.282609 ┆ 87       ┆ 184        │
│ Third  ┆ 24.236253 ┆ 119      ┆ 491        │
└────────┴───────────┴──────────┴────────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 첫 번째 y축에 전체승객수와 생존자수 막대 그래프
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프 생성
sns.barplot(data=survival_analysis, x='class', y='전체승객수', color='lightblue', alpha=0.5, ax=ax1, label='전체승객수')
sns.barplot(data=survival_analysis, x='class', y='생존자수', color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 생존율 선 그래프
ax2.plot(range(len(survival_analysis)), survival_analysis['생존율'], color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 객실 등급별 생존율과 승객수', pad=15)
ax1.set_xlabel('객실 등급')
ax1.set_ylabel('승객수')
ax2.set_ylabel('생존율 (%)')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 첫 번째 y축에 전체승객수와 생존자수 막대 그래프
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프 생성
sns.barplot(data=survival_analysis, x='class', y='전체승객수', color='lightblue', alpha=0.5, ax=ax1, label='전체승객수')
sns.barplot(data=survival_analysis, x='class', y='생존자수', color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 생존율 선 그래프
ax2.plot(range(len(survival_analysis)), survival_analysis['생존율'], color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 객실 등급별 생존율과 승객수', pad=15)
ax1.set_xlabel('객실 등급')
ax1.set_ylabel('승객수')
ax2.set_ylabel('생존율 (%)')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.show()

5. 성별/객실등급별 생존율

gender_class_analysis = (
    titanic_df.group_by(['sex', 'class'])
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort(['sex', '생존율'], descending=True)
)
print("성별/객실등급별 생존율:")
print(gender_class_analysis)
gender_class_analysis = (
    titanic_df.group_by(['sex', 'class'])
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort(['sex', '생존율'], descending=True)
)
print("성별/객실등급별 생존율:")
print(gender_class_analysis)
성별/객실등급별 생존율:
shape: (6, 5)
┌────────┬────────┬───────────┬──────────┬────────┐
│ sex    ┆ class  ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---    ┆ ---    ┆ ---       ┆ ---      ┆ ---    │
│ str    ┆ cat    ┆ f64       ┆ i64      ┆ u32    │
╞════════╪════════╪═══════════╪══════════╪════════╡
│ male   ┆ First  ┆ 36.885246 ┆ 45       ┆ 122    │
│ male   ┆ Second ┆ 15.740741 ┆ 17       ┆ 108    │
│ male   ┆ Third  ┆ 13.544669 ┆ 47       ┆ 347    │
│ female ┆ First  ┆ 96.808511 ┆ 91       ┆ 94     │
│ female ┆ Second ┆ 92.105263 ┆ 70       ┆ 76     │
│ female ┆ Third  ┆ 50.0      ┆ 72       ┆ 144    │
└────────┴────────┴───────────┴──────────┴────────┘
성별/객실등급별 생존율:
shape: (6, 5)
┌────────┬────────┬───────────┬──────────┬────────┐
│ sex    ┆ class  ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---    ┆ ---    ┆ ---       ┆ ---      ┆ ---    │
│ str    ┆ cat    ┆ f64       ┆ i64      ┆ u32    │
╞════════╪════════╪═══════════╪══════════╪════════╡
│ male   ┆ First  ┆ 36.885246 ┆ 45       ┆ 122    │
│ male   ┆ Second ┆ 15.740741 ┆ 17       ┆ 108    │
│ male   ┆ Third  ┆ 13.544669 ┆ 47       ┆ 347    │
│ female ┆ First  ┆ 96.808511 ┆ 91       ┆ 94     │
│ female ┆ Second ┆ 92.105263 ┆ 70       ┆ 76     │
│ female ┆ Third  ┆ 50.0      ┆ 72       ┆ 144    │
└────────┴────────┴───────────┴──────────┴────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 성별에 따라 다른 색상 사용하여 막대 그래프 생성
colors = {'male': 'skyblue', 'female': 'lightcoral'}
ax = sns.barplot(data=gender_class_analysis,
               x='class',
               y='생존율',
               hue='sex',
               palette=colors)
 
# 그래프 꾸미기
plt.title('타이타닉 성별/객실등급별 생존율', pad=15, size=15)
plt.xlabel('객실 등급', size=12)
plt.ylabel('생존율 (%)', size=12)
 
# 막대 위에 생존율 표시
for container in ax.containers:
   ax.bar_label(container, fmt='%.1f%%', padding=3)
 
# 범례 제목 수정
plt.legend(title='성별')
 
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 성별에 따라 다른 색상 사용하여 막대 그래프 생성
colors = {'male': 'skyblue', 'female': 'lightcoral'}
ax = sns.barplot(data=gender_class_analysis,
               x='class',
               y='생존율',
               hue='sex',
               palette=colors)
 
# 그래프 꾸미기
plt.title('타이타닉 성별/객실등급별 생존율', pad=15, size=15)
plt.xlabel('객실 등급', size=12)
plt.ylabel('생존율 (%)', size=12)
 
# 막대 위에 생존율 표시
for container in ax.containers:
   ax.bar_label(container, fmt='%.1f%%', padding=3)
 
# 범례 제목 수정
plt.legend(title='성별')
 
plt.show()

6. 연령대별 분석

age_analysis = (
    titanic_df.with_columns([
        pl.col('age')
        .cut(breaks=[0, 10, 20, 30, 40, 50, 60, 100],
             labels=['0', '0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '60-70', '70+'])
        .alias('age_group')
    ])
    .group_by('age_group')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('age_group')
)
print("연령대별 생존율:")
print(age_analysis)
age_analysis = (
    titanic_df.with_columns([
        pl.col('age')
        .cut(breaks=[0, 10, 20, 30, 40, 50, 60, 100],
             labels=['0', '0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '60-70', '70+'])
        .alias('age_group')
    ])
    .group_by('age_group')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('age_group')
)
print("연령대별 생존율:")
print(age_analysis)
연령대별 생존율:
shape: (7, 4)
┌───────────┬───────────┬──────────┬────────┐
│ age_group ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---       ┆ ---       ┆ ---      ┆ ---    │
│ cat       ┆ f64       ┆ i64      ┆ u32    │
╞═══════════╪═══════════╪══════════╪════════╡
│ 0-10      ┆ 59.375    ┆ 38       ┆ 64     │
│ 11-20     ┆ 38.26087  ┆ 44       ┆ 115    │
│ 21-30     ┆ 33.415233 ┆ 136      ┆ 407    │
│ 31-40     ┆ 44.516129 ┆ 69       ┆ 155    │
│ 41-50     ┆ 38.372093 ┆ 33       ┆ 86     │
│ 51-60     ┆ 40.47619  ┆ 17       ┆ 42     │
│ 60-70     ┆ 22.727273 ┆ 5        ┆ 22     │
└───────────┴───────────┴──────────┴────────┘
연령대별 생존율:
shape: (7, 4)
┌───────────┬───────────┬──────────┬────────┐
│ age_group ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---       ┆ ---       ┆ ---      ┆ ---    │
│ cat       ┆ f64       ┆ i64      ┆ u32    │
╞═══════════╪═══════════╪══════════╪════════╡
│ 0-10      ┆ 59.375    ┆ 38       ┆ 64     │
│ 11-20     ┆ 38.26087  ┆ 44       ┆ 115    │
│ 21-30     ┆ 33.415233 ┆ 136      ┆ 407    │
│ 31-40     ┆ 44.516129 ┆ 69       ┆ 155    │
│ 41-50     ┆ 38.372093 ┆ 33       ┆ 86     │
│ 51-60     ┆ 40.47619  ┆ 17       ┆ 42     │
│ 60-70     ┆ 22.727273 ┆ 5        ┆ 22     │
└───────────┴───────────┴──────────┴────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 생존자수
sns.barplot(data=age_analysis, x='age_group', y='승객수', color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
sns.barplot(data=age_analysis, x='age_group', y='생존자수', color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 선 그래프: 생존율
ax2.plot(range(len(age_analysis)), age_analysis['생존율'], color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 연령대별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('연령대', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(age_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 생존자수
sns.barplot(data=age_analysis, x='age_group', y='승객수', color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
sns.barplot(data=age_analysis, x='age_group', y='생존자수', color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 선 그래프: 생존율
ax2.plot(range(len(age_analysis)), age_analysis['생존율'], color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 연령대별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('연령대', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(age_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()

7. 동반가족 분석

family_analysis = (
    titanic_df.with_columns([
        (pl.col('sibsp') + pl.col('parch')).alias('family_size')
    ])
    .group_by('family_size')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('family_size')
)
print("동반가족 수별 생존율:")
print(family_analysis)
family_analysis = (
    titanic_df.with_columns([
        (pl.col('sibsp') + pl.col('parch')).alias('family_size')
    ])
    .group_by('family_size')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('family_size')
)
print("동반가족 수별 생존율:")
print(family_analysis)
동반가족 수별 생존율:
shape: (9, 4)
┌─────────────┬───────────┬──────────┬────────┐
│ family_size ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---         ┆ ---       ┆ ---      ┆ ---    │
│ i64         ┆ f64       ┆ i64      ┆ u32    │
╞═════════════╪═══════════╪══════════╪════════╡
│ 0           ┆ 30.353818 ┆ 163      ┆ 537    │
│ 1           ┆ 55.279503 ┆ 89       ┆ 161    │
│ 2           ┆ 57.843137 ┆ 59       ┆ 102    │
│ 3           ┆ 72.413793 ┆ 21       ┆ 29     │
│ 4           ┆ 20.0      ┆ 3        ┆ 15     │
│ 5           ┆ 13.636364 ┆ 3        ┆ 22     │
│ 6           ┆ 33.333333 ┆ 4        ┆ 12     │
│ 7           ┆ 0.0       ┆ 0        ┆ 6      │
│ 10          ┆ 0.0       ┆ 0        ┆ 7      │
└─────────────┴───────────┴──────────┴────────┘
동반가족 수별 생존율:
shape: (9, 4)
┌─────────────┬───────────┬──────────┬────────┐
│ family_size ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---         ┆ ---       ┆ ---      ┆ ---    │
│ i64         ┆ f64       ┆ i64      ┆ u32    │
╞═════════════╪═══════════╪══════════╪════════╡
│ 0           ┆ 30.353818 ┆ 163      ┆ 537    │
│ 1           ┆ 55.279503 ┆ 89       ┆ 161    │
│ 2           ┆ 57.843137 ┆ 59       ┆ 102    │
│ 3           ┆ 72.413793 ┆ 21       ┆ 29     │
│ 4           ┆ 20.0      ┆ 3        ┆ 15     │
│ 5           ┆ 13.636364 ┆ 3        ┆ 22     │
│ 6           ┆ 33.333333 ┆ 4        ┆ 12     │
│ 7           ┆ 0.0       ┆ 0        ┆ 6      │
│ 10          ┆ 0.0       ┆ 0        ┆ 7      │
└─────────────┴───────────┴──────────┴────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수
bars = sns.barplot(data=family_analysis, x='family_size', y='승객수',
                 color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
 
# 선 그래프: 생존율
line = ax2.plot(range(len(family_analysis)), family_analysis['생존율'],
               color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 동반가족 수별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('동반가족 수', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(family_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수
bars = sns.barplot(data=family_analysis, x='family_size', y='승객수',
                 color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
 
# 선 그래프: 생존율
line = ax2.plot(range(len(family_analysis)), family_analysis['생존율'],
               color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 동반가족 수별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('동반가족 수', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(family_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()

8. 승선항구별 분석

embarked_analysis = (
    titanic_df.group_by('embarked')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('fare').mean().alias('평균_요금'),
        pl.count().alias('승객수')
    ])
    .sort('생존율', descending=True)
)
print("승선항구별 분석:")
print(embarked_analysis)
embarked_analysis = (
    titanic_df.group_by('embarked')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('fare').mean().alias('평균_요금'),
        pl.count().alias('승객수')
    ])
    .sort('생존율', descending=True)
)
print("승선항구별 분석:")
print(embarked_analysis)
승선항구별 분석:
shape: (3, 4)
┌──────────┬───────────┬───────────┬────────┐
│ embarked ┆ 생존율    ┆ 평균_요금 ┆ 승객수 │
│ ---      ┆ ---       ┆ ---       ┆ ---    │
│ str      ┆ f64       ┆ f64       ┆ u32    │
╞══════════╪═══════════╪═══════════╪════════╡
│ C        ┆ 55.357143 ┆ 59.954144 ┆ 168    │
│ Q        ┆ 38.961039 ┆ 13.27603  ┆ 77     │
│ S        ┆ 33.900929 ┆ 27.243651 ┆ 646    │
└──────────┴───────────┴───────────┴────────┘
승선항구별 분석:
shape: (3, 4)
┌──────────┬───────────┬───────────┬────────┐
│ embarked ┆ 생존율    ┆ 평균_요금 ┆ 승객수 │
│ ---      ┆ ---       ┆ ---       ┆ ---    │
│ str      ┆ f64       ┆ f64       ┆ u32    │
╞══════════╪═══════════╪═══════════╪════════╡
│ C        ┆ 55.357143 ┆ 59.954144 ┆ 168    │
│ Q        ┆ 38.961039 ┆ 13.27603  ┆ 77     │
│ S        ┆ 33.900929 ┆ 27.243651 ┆ 646    │
└──────────┴───────────┴───────────┴────────┘
# null 값을 제외한 데이터로 분석 (의미있는 분석을 위해)
embarked_analysis_filtered = embarked_analysis.filter(pl.col('embarked').is_not_null())
 
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 평균 요금
x = range(len(embarked_analysis_filtered))
width = 0.35
 
ax1.bar([i-width/2 for i in x], embarked_analysis_filtered['승객수'],
       width, color='lightblue', label='승객수')
ax2.bar([i+width/2 for i in x], embarked_analysis_filtered['평균_요금'],
       width, color='lightgreen', label='평균 요금')
 
# 생존율 선 그래프
ax1.plot(x, embarked_analysis_filtered['생존율'], 'ro-', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 승선항구별 분석', pad=15, size=15)
ax1.set_xlabel('승선항구', size=12)
ax1.set_ylabel('승객수 / 생존율(%)', size=12)
ax2.set_ylabel('평균 요금(파운드)', size=12)
 
# x축 레이블 설정
plt.xticks(x, embarked_analysis_filtered['embarked'])
 
# 데이터 레이블 표시
for i in x:
   # 생존율 표시
   ax1.text(i, embarked_analysis_filtered['생존율'][i],
            f"{embarked_analysis_filtered['생존율'][i]:.1f}%",
            ha='center', va='bottom')
   # 승객수 표시
   ax1.text(i-width/2, embarked_analysis_filtered['승객수'][i]/2,
            f"{embarked_analysis_filtered['승객수'][i]}",
            ha='center', va='center')
   # 평균 요금 표시
   ax2.text(i+width/2, embarked_analysis_filtered['평균_요금'][i]/2,
            f{embarked_analysis_filtered['평균_요금'][i]:.1f}",
            ha='center', va='center')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()
# null 값을 제외한 데이터로 분석 (의미있는 분석을 위해)
embarked_analysis_filtered = embarked_analysis.filter(pl.col('embarked').is_not_null())
 
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 평균 요금
x = range(len(embarked_analysis_filtered))
width = 0.35
 
ax1.bar([i-width/2 for i in x], embarked_analysis_filtered['승객수'],
       width, color='lightblue', label='승객수')
ax2.bar([i+width/2 for i in x], embarked_analysis_filtered['평균_요금'],
       width, color='lightgreen', label='평균 요금')
 
# 생존율 선 그래프
ax1.plot(x, embarked_analysis_filtered['생존율'], 'ro-', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 승선항구별 분석', pad=15, size=15)
ax1.set_xlabel('승선항구', size=12)
ax1.set_ylabel('승객수 / 생존율(%)', size=12)
ax2.set_ylabel('평균 요금(파운드)', size=12)
 
# x축 레이블 설정
plt.xticks(x, embarked_analysis_filtered['embarked'])
 
# 데이터 레이블 표시
for i in x:
   # 생존율 표시
   ax1.text(i, embarked_analysis_filtered['생존율'][i],
            f"{embarked_analysis_filtered['생존율'][i]:.1f}%",
            ha='center', va='bottom')
   # 승객수 표시
   ax1.text(i-width/2, embarked_analysis_filtered['승객수'][i]/2,
            f"{embarked_analysis_filtered['승객수'][i]}",
            ha='center', va='center')
   # 평균 요금 표시
   ax2.text(i+width/2, embarked_analysis_filtered['평균_요금'][i]/2,
            f{embarked_analysis_filtered['평균_요금'][i]:.1f}",
            ha='center', va='center')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()

9. 요금구간별 분석

fare_analysis = (
    titanic_df.with_columns([
        pl.col('fare')
        .cut(breaks=[0, 20, 50, 100, 200, 1000],
             labels=['0', '0-20', '21-50', '51-100', '101-200', '200-300', '300+'])
        .alias('fare_group')
    ])
    .group_by('fare_group')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('fare_group')
)
print("요금구간별 생존율:")
print(fare_analysis)
fare_analysis = (
    titanic_df.with_columns([
        pl.col('fare')
        .cut(breaks=[0, 20, 50, 100, 200, 1000],
             labels=['0', '0-20', '21-50', '51-100', '101-200', '200-300', '300+'])
        .alias('fare_group')
    ])
    .group_by('fare_group')
    .agg([
        (pl.col('survived').mean() * 100).alias('생존율'),
        pl.col('survived').sum().alias('생존자수'),
        pl.count().alias('승객수')
    ])
    .sort('fare_group')
)
print("요금구간별 생존율:")
print(fare_analysis)
요금구간별 생존율:
shape: (6, 4)
┌────────────┬───────────┬──────────┬────────┐
│ fare_group ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---        ┆ ---       ┆ ---      ┆ ---    │
│ cat        ┆ f64       ┆ i64      ┆ u32    │
╞════════════╪═══════════╪══════════╪════════╡
│ 0          ┆ 6.666667  ┆ 1        ┆ 15     │
│ 0-20       ┆ 28.4      ┆ 142      ┆ 500    │
│ 21-50      ┆ 41.666667 ┆ 90       ┆ 216    │
│ 51-100     ┆ 65.420561 ┆ 70       ┆ 107    │
│ 101-200    ┆ 75.757576 ┆ 25       ┆ 33     │
│ 200-300    ┆ 70.0      ┆ 14       ┆ 20     │
└────────────┴───────────┴──────────┴────────┘
요금구간별 생존율:
shape: (6, 4)
┌────────────┬───────────┬──────────┬────────┐
│ fare_group ┆ 생존율    ┆ 생존자수 ┆ 승객수 │
│ ---        ┆ ---       ┆ ---      ┆ ---    │
│ cat        ┆ f64       ┆ i64      ┆ u32    │
╞════════════╪═══════════╪══════════╪════════╡
│ 0          ┆ 6.666667  ┆ 1        ┆ 15     │
│ 0-20       ┆ 28.4      ┆ 142      ┆ 500    │
│ 21-50      ┆ 41.666667 ┆ 90       ┆ 216    │
│ 51-100     ┆ 65.420561 ┆ 70       ┆ 107    │
│ 101-200    ┆ 75.757576 ┆ 25       ┆ 33     │
│ 200-300    ┆ 70.0      ┆ 14       ┆ 20     │
└────────────┴───────────┴──────────┴────────┘
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 생존자수
sns.barplot(data=fare_analysis, x='fare_group', y='승객수',
           color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
sns.barplot(data=fare_analysis, x='fare_group', y='생존자수',
           color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 선 그래프: 생존율
line = ax2.plot(range(len(fare_analysis)), fare_analysis['생존율'],
               color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 요금구간별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('요금구간', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(fare_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(12, 6))
 
# 막대 그래프와 선 그래프를 결합하여 표시
ax1 = plt.gca()
ax2 = ax1.twinx()
 
# 막대 그래프: 승객수와 생존자수
sns.barplot(data=fare_analysis, x='fare_group', y='승객수',
           color='lightblue', alpha=0.5, ax=ax1, label='전체 승객수')
sns.barplot(data=fare_analysis, x='fare_group', y='생존자수',
           color='blue', alpha=0.3, ax=ax1, label='생존자수')
 
# 선 그래프: 생존율
line = ax2.plot(range(len(fare_analysis)), fare_analysis['생존율'],
               color='red', marker='o', linewidth=2, label='생존율')
 
# 그래프 꾸미기
plt.title('타이타닉 요금구간별 생존율과 승객수', pad=15, size=15)
ax1.set_xlabel('요금구간', size=12)
ax1.set_ylabel('승객수', size=12)
ax2.set_ylabel('생존율 (%)', size=12)
 
# 생존율 데이터 레이블 표시
for i, v in enumerate(fare_analysis['생존율']):
   ax2.text(i, v, f'{v:.1f}%', ha='center', va='bottom')
 
# 범례 표시
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')
 
plt.tight_layout()
plt.show()

10. 종합 통계

summary_stats = {
    '전체_승객수': titanic_df.shape[0],
    '전체_생존율': round((titanic_df['survived'].mean() * 100),2),
    '여성_생존율': round((titanic_df.filter(pl.col('sex') == 'female')['survived'].mean() * 100),2),
    '남성_생존율': round((titanic_df.filter(pl.col('sex') == 'male')['survived'].mean() * 100),2),
    '평균_연령': round(titanic_df['age'].mean(),2),
    '평균_요금': round(titanic_df['fare'].mean(),2),
    '최다_승선항구': titanic_df['embarked'].value_counts().filter(pl.col('count') == pl.col('count').max())['embarked'][0]
}
print("종합 통계:")
print(summary_stats)
summary_stats = {
    '전체_승객수': titanic_df.shape[0],
    '전체_생존율': round((titanic_df['survived'].mean() * 100),2),
    '여성_생존율': round((titanic_df.filter(pl.col('sex') == 'female')['survived'].mean() * 100),2),
    '남성_생존율': round((titanic_df.filter(pl.col('sex') == 'male')['survived'].mean() * 100),2),
    '평균_연령': round(titanic_df['age'].mean(),2),
    '평균_요금': round(titanic_df['fare'].mean(),2),
    '최다_승선항구': titanic_df['embarked'].value_counts().filter(pl.col('count') == pl.col('count').max())['embarked'][0]
}
print("종합 통계:")
print(summary_stats)
종합 통계:
{'전체_승객수': 891, '전체_생존율': 38.38, '여성_생존율': 74.2, '남성_생존율': 18.89, '평균_연령': 29.7, '평균_요금': 32.2, '최다_승선항구': 'S'}
종합 통계:
{'전체_승객수': 891, '전체_생존율': 38.38, '여성_생존율': 74.2, '남성_생존율': 18.89, '평균_연령': 29.7, '평균_요금': 32.2, '최다_승선항구': 'S'}

11. 생존자 특성 분석

survivor_profile = (
    titanic_df.filter(pl.col('survived') == 1)
    .group_by(['class', 'sex'])
    .agg([
        pl.col('age').mean().alias('평균_연령'),
        pl.col('fare').mean().alias('평균_요금'),
        pl.count().alias('생존자수')
    ])
    .sort(['class', 'sex'])
)
print("생존자 프로필 분석:")
print(survivor_profile)
survivor_profile = (
    titanic_df.filter(pl.col('survived') == 1)
    .group_by(['class', 'sex'])
    .agg([
        pl.col('age').mean().alias('평균_연령'),
        pl.col('fare').mean().alias('평균_요금'),
        pl.count().alias('생존자수')
    ])
    .sort(['class', 'sex'])
)
print("생존자 프로필 분석:")
print(survivor_profile)
생존자 프로필 분석:
shape: (6, 5)
┌────────┬────────┬───────────┬────────────┬──────────┐
│ class  ┆ sex    ┆ 평균_연령 ┆ 평균_요금  ┆ 생존자수 │
│ ---    ┆ ---    ┆ ---       ┆ ---        ┆ ---      │
│ cat    ┆ str    ┆ f64       ┆ f64        ┆ u32      │
╞════════╪════════╪═══════════╪════════════╪══════════╡
│ First  ┆ female ┆ 34.420792 ┆ 105.978159 ┆ 91       │
│ First  ┆ male   ┆ 35.520346 ┆ 74.63732   ┆ 45       │
│ Second ┆ female ┆ 28.127118 ┆ 22.288989  ┆ 70       │
│ Second ┆ male   ┆ 17.631073 ┆ 21.0951    ┆ 17       │
│ Third  ┆ female ┆ 22.930249 ┆ 12.464526  ┆ 72       │
│ Third  ┆ male   ┆ 23.696001 ┆ 15.579696  ┆ 47       │
└────────┴────────┴───────────┴────────────┴──────────┘
생존자 프로필 분석:
shape: (6, 5)
┌────────┬────────┬───────────┬────────────┬──────────┐
│ class  ┆ sex    ┆ 평균_연령 ┆ 평균_요금  ┆ 생존자수 │
│ ---    ┆ ---    ┆ ---       ┆ ---        ┆ ---      │
│ cat    ┆ str    ┆ f64       ┆ f64        ┆ u32      │
╞════════╪════════╪═══════════╪════════════╪══════════╡
│ First  ┆ female ┆ 34.420792 ┆ 105.978159 ┆ 91       │
│ First  ┆ male   ┆ 35.520346 ┆ 74.63732   ┆ 45       │
│ Second ┆ female ┆ 28.127118 ┆ 22.288989  ┆ 70       │
│ Second ┆ male   ┆ 17.631073 ┆ 21.0951    ┆ 17       │
│ Third  ┆ female ┆ 22.930249 ┆ 12.464526  ┆ 72       │
│ Third  ┆ male   ┆ 23.696001 ┆ 15.579696  ┆ 47       │
└────────┴────────┴───────────┴────────────┴──────────┘
# 그래프 크기 설정
plt.figure(figsize=(15, 6))
 
# 서브플롯 생성
plt.subplot(1, 2, 1)
 
# 첫 번째 그래프: 평균 연령과 평균 요금
x = range(len(survivor_profile))
width = 0.35
 
# 막대 그래프 생성
plt.bar([i-width/2 for i in x], survivor_profile['평균_연령'],
        width, label='평균 연령', color='lightblue')
plt.bar([i+width/2 for i in x], survivor_profile['평균_요금'],
        width, label='평균 요금', color='lightgreen')
 
# 그래프 꾸미기
plt.title('생존자 평균 연령 및 요금', pad=15)
plt.xticks(x, [f"{row[0]}\n{row[1]}" for row in survivor_profile.iter_rows()])  # 인덱스로 접근
plt.ylabel('연령(세) / 요금(파운드)')
plt.legend()
 
# 데이터 레이블 추가
for i in x:
    plt.text(i-width/2, survivor_profile['평균_연령'][i],
             f"{survivor_profile['평균_연령'][i]:.1f}",
             ha='center', va='bottom')
    plt.text(i+width/2, survivor_profile['평균_요금'][i],
             f{survivor_profile['평균_요금'][i]:.1f}",
             ha='center', va='bottom')
 
# 두 번째 그래프: 생존자 수
plt.subplot(1, 2, 2)
 
# 성별로 구분된 막대 그래프
females = survivor_profile.filter(pl.col('sex') == 'female')
males = survivor_profile.filter(pl.col('sex') == 'male')
 
x = range(3)
width = 0.35
 
plt.bar([i-width/2 for i in x], females['생존자수'],
        width, label='여성', color='lightcoral')
plt.bar([i+width/2 for i in x], males['생존자수'],
        width, label='남성', color='skyblue')
 
# 그래프 꾸미기
plt.title('객실 등급별 성별 생존자 수', pad=15)
plt.xticks(x, ['First', 'Second', 'Third'])
plt.ylabel('생존자 수')
plt.legend()
 
# 데이터 레이블 추가
for i in x:
    plt.text(i-width/2, females['생존자수'][i],
             str(females['생존자수'][i]),
             ha='center', va='bottom')
    plt.text(i+width/2, males['생존자수'][i],
             str(males['생존자수'][i]),
             ha='center', va='bottom')
 
plt.tight_layout()
plt.show()
# 그래프 크기 설정
plt.figure(figsize=(15, 6))
 
# 서브플롯 생성
plt.subplot(1, 2, 1)
 
# 첫 번째 그래프: 평균 연령과 평균 요금
x = range(len(survivor_profile))
width = 0.35
 
# 막대 그래프 생성
plt.bar([i-width/2 for i in x], survivor_profile['평균_연령'],
        width, label='평균 연령', color='lightblue')
plt.bar([i+width/2 for i in x], survivor_profile['평균_요금'],
        width, label='평균 요금', color='lightgreen')
 
# 그래프 꾸미기
plt.title('생존자 평균 연령 및 요금', pad=15)
plt.xticks(x, [f"{row[0]}\n{row[1]}" for row in survivor_profile.iter_rows()])  # 인덱스로 접근
plt.ylabel('연령(세) / 요금(파운드)')
plt.legend()
 
# 데이터 레이블 추가
for i in x:
    plt.text(i-width/2, survivor_profile['평균_연령'][i],
             f"{survivor_profile['평균_연령'][i]:.1f}",
             ha='center', va='bottom')
    plt.text(i+width/2, survivor_profile['평균_요금'][i],
             f{survivor_profile['평균_요금'][i]:.1f}",
             ha='center', va='bottom')
 
# 두 번째 그래프: 생존자 수
plt.subplot(1, 2, 2)
 
# 성별로 구분된 막대 그래프
females = survivor_profile.filter(pl.col('sex') == 'female')
males = survivor_profile.filter(pl.col('sex') == 'male')
 
x = range(3)
width = 0.35
 
plt.bar([i-width/2 for i in x], females['생존자수'],
        width, label='여성', color='lightcoral')
plt.bar([i+width/2 for i in x], males['생존자수'],
        width, label='남성', color='skyblue')
 
# 그래프 꾸미기
plt.title('객실 등급별 성별 생존자 수', pad=15)
plt.xticks(x, ['First', 'Second', 'Third'])
plt.ylabel('생존자 수')
plt.legend()
 
# 데이터 레이블 추가
for i in x:
    plt.text(i-width/2, females['생존자수'][i],
             str(females['생존자수'][i]),
             ha='center', va='bottom')
    plt.text(i+width/2, males['생존자수'][i],
             str(males['생존자수'][i]),
             ha='center', va='bottom')
 
plt.tight_layout()
plt.show()
{"packages":["numpy","pandas","matplotlib","lxml"]}
4.1 EDA(탐색적 데이터 분석)4.3 Tips 데이터 분석