上一節(jié)已經(jīng)用用邏輯回歸算法預(yù)測泰坦尼克號人員存活情況,但是不了解什么樣的人容易存活;因此,用數(shù)據(jù)分析方法繼續(xù)探究數(shù)據(jù)背后隱藏的秘密,并用數(shù)據(jù)可視化方法展示出來。
目錄
- 提出問題
- 理解數(shù)據(jù)
- 采集數(shù)據(jù)
- 導(dǎo)入數(shù)據(jù)
- 查看數(shù)據(jù)
- 數(shù)據(jù)清洗
- 數(shù)據(jù)處理
- 幸存率與家庭類別
- 幸存率與頭銜
- 幸存率與年齡
- 幸存率與客艙等級
- 幸存率與性別
- 幸存率與登船港口
1. 提出問題
什么樣的人更容易存活?
2. 理解數(shù)據(jù)
2.1 采集數(shù)據(jù)
點(diǎn)擊此鏈接進(jìn)入kaggle的titanic項(xiàng)目下載數(shù)據(jù)集
2.2 導(dǎo)入數(shù)據(jù)
#導(dǎo)入處理數(shù)據(jù)包
import numpy as np
import pandas as pd
train=pd.read_csv('E:\\titanic\\train.csv')
print('訓(xùn)練數(shù)據(jù)集:',train.shape)
訓(xùn)練數(shù)據(jù)集: (891, 12)
2.3 查看數(shù)據(jù)集信息
2.3.1 查看數(shù)據(jù)集前幾行數(shù)據(jù)
train.head()
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 |
2.3.2 查看數(shù)值型數(shù)據(jù)的描述性統(tǒng)計(jì)信息
train.describe()
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 |
Age列有714個(gè)數(shù)據(jù),說明有缺失值;
Fare票價(jià)最低是0元,說明有異常值。
2.3.3 查看數(shù)據(jù)每一列的數(shù)據(jù)總和和數(shù)據(jù)類型
train.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 PassengerId 891 non-null int64
1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null object
4 Sex 891 non-null object
5 Age 714 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null object
9 Fare 891 non-null float64
10 Cabin 204 non-null object
11 Embarked 889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 66.2+ KB
發(fā)現(xiàn)Age、Cabin和Embarked有缺失值,需要進(jìn)行數(shù)據(jù)清洗
3. 數(shù)據(jù)清洗
3.1 缺失值處理
3.1.1 數(shù)值型缺失值處理,簡單的方法用平均值代替
train['Age']=train['Age'].fillna(train['Age'].mean())
3.1.2 字符串型缺失值處理
3.1.2.1 Embarked缺失值處理
Embarked只缺失兩個(gè)值,可用最多的值代替
train['Embarked'].value_counts()
S 644
C 168
Q 77
Name: Embarked, dtype: int64
#S最多,選擇用S來填充缺失值
train['Embarked']=train['Embarked'].fillna('S')
3.1.2.2 Cabin缺失值處理
因Cabin缺失值較多,選擇用U(Uknow)來填充
train['Cabin']=train['Cabin'].fillna('U')
#查看缺失值處理后的結(jié)果
train.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 PassengerId 891 non-null int64
1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null object
4 Sex 891 non-null object
5 Age 891 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null object
9 Fare 891 non-null float64
10 Cabin 891 non-null object
11 Embarked 891 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 66.2+ KB
train.head()
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 | U | 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 | U | 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 | U | S |
3.2 異常值處理
#查看Fare等于0的有多少個(gè)
train[train['Fare']==0].shape[0]
15
只有15個(gè)比較少,選擇保留不做處理
4. 數(shù)據(jù)分析
數(shù)據(jù)庫里有10個(gè)指標(biāo)與乘客信息有關(guān)
其中以下三個(gè)指標(biāo)不進(jìn)行分析:
Ticket(票號):無法分類,沒有參考價(jià)值;Fare(票價(jià)):票價(jià)由客艙等級決定,不必重復(fù)分析;Cabin(客艙號):缺失值數(shù)量太多,沒有分析價(jià)值。
下面對家庭類別、頭銜、年齡、客艙等級、性別、登船港口6個(gè)指標(biāo)分別進(jìn)行分析
4.1 家庭類別與生存率的關(guān)系
4.1.1 家庭分組
#存放家庭信息
familyDf = pd.DataFrame()
'''
家庭人數(shù)=同代直系親屬數(shù)(Parch)+不同代直系親屬數(shù)(SibSp)+乘客自己
(因?yàn)槌丝妥约阂彩羌彝コ蓡T的一個(gè),所以這里加1)
'''
familyDf[ 'FamilySize' ] = train[ 'Parch' ] + train[ 'SibSp' ] + 1
'''
家庭類別:
小家庭Family_Single:家庭人數(shù)=1
中等家庭Family_Small: 2<=家庭人數(shù)<=4
大家庭Family_Large: 家庭人數(shù)>=5
'''
# 定義家庭分組用的函數(shù)
def familyGroup(FS):
if FS==1:
return 'Family_Single'
elif 2<=FS<=4:
return 'Family_Small'
else:
return 'Family_Large'
#map函數(shù)主要作用是使用自定義函數(shù)
familyDf['FamilyCategory'] = familyDf['FamilySize'].map(familyGroup)
familyDf.head()
FamilySize | FamilyCategory | |
---|---|---|
0 | 2 | Family_Small |
1 | 2 | Family_Small |
2 | 1 | Family_Single |
3 | 2 | Family_Small |
4 | 1 | Family_Single |
將得到的familyDf分組添加到train數(shù)據(jù)集中
train = pd.concat([train,familyDf],axis=1)
train.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | FamilySize | FamilyCategory | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | U | S | 2 | Family_Small |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 2 | Family_Small |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | U | S | 1 | Family_Single |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S | 2 | Family_Small |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | U | S | 1 | Family_Single |
4.1.2 匯總家庭類別與是否幸存的人數(shù)
DataFrame的pivot_table方法可用于匯總統(tǒng)計(jì),類似于Excel的數(shù)據(jù)透視表,參數(shù)如下:
- 第1個(gè)參數(shù):需要匯總統(tǒng)計(jì)的數(shù)據(jù)源
- index : 透視表的行索引,必要參數(shù),如果我們想要設(shè)置多層次索引,使用列表[ ]
- values : 對目標(biāo)數(shù)據(jù)進(jìn)行篩選,默認(rèn)是全部數(shù)據(jù),我們可通過values參數(shù)設(shè)置我們想要展示的數(shù)據(jù)列
- columns :透視表的列索引,非必要參數(shù),同index使用方式一樣
- aggfunc :對數(shù)據(jù)聚合時(shí)進(jìn)行的函數(shù)操作,默認(rèn)是求平均值,也可以sum、count等
- margins :額外列,在最邊上,默認(rèn)是對行列求和
- fill_value : 對于空值進(jìn)行填充
- dropna : 默認(rèn)開啟去重
# 匯總統(tǒng)計(jì)家庭類別與是否幸存的人數(shù)
FamilyCgDf = pd.pivot_table(train,
index='FamilyCategory',
columns='Survived',
values='PassengerId',
aggfunc='count')
FamilyCgDf
Survived | 0 | 1 |
---|---|---|
FamilyCategory | ||
Family_Large | 52 | 10 |
Family_Single | 374 | 163 |
Family_Small | 123 | 169 |
# 匯總統(tǒng)計(jì)家庭類別與是否幸存的人數(shù)
FamilyCgDf_1 = pd.pivot_table(train,
index='FamilyCategory',
columns='Survived',
values='FamilySize',
aggfunc='count')
FamilyCgDf_1
Survived | 0 | 1 |
---|---|---|
FamilyCategory | ||
Family_Large | 52 | 10 |
Family_Single | 374 | 163 |
Family_Small | 123 | 169 |
4.1.3 匯總統(tǒng)計(jì)家庭類別的存活率
DataFrame的div函數(shù)用于數(shù)據(jù)框除以其他元素后的值,主要有2個(gè)參數(shù):
- other:標(biāo)量 (scalar),序列(sequence),Series或DataFrame,任何單個(gè)或多個(gè)元素?cái)?shù)據(jù)結(jié)構(gòu)或類似列表的對象。
- axis:0 或‘index’, 1 或‘columns’,是否通過索引 (0 or‘index’) 或列(1 或‘columns’)進(jìn)行比較。對于Series輸入,軸匹配Series索引。
# div函數(shù)用法1:除以同一個(gè)值
FamilyCgDf.div(10)
Survived | 0 | 1 |
---|---|---|
FamilyCategory | ||
Family_Large | 5.2 | 1.0 |
Family_Single | 37.4 | 16.3 |
Family_Small | 12.3 | 16.9 |
# div函數(shù)用法2:根據(jù)不同索引,除以不同值
otherS = pd.Series([10,100,1000],index=['Family_Large','Family_Single','Family_Small'])
FamilyCgDf.div(otherS,axis='index')
Survived | 0 | 1 |
---|---|---|
FamilyCategory | ||
Family_Large | 5.200 | 1.000 |
Family_Single | 3.740 | 1.630 |
Family_Small | 0.123 | 0.169 |
以上代碼表示FamilyCgDf數(shù)據(jù)框的3行索引的值分別除以10、100和1000。 同理,可設(shè)置索引的值分別除以所在行的求和值:
# 匯總統(tǒng)計(jì)家庭類別與是否幸存的比例
FamilyCgDf2 = FamilyCgDf.div(FamilyCgDf.sum(axis=1),axis=0)
FamilyCgDf2
Survived | 0 | 1 |
---|---|---|
FamilyCategory | ||
Family_Large | 0.838710 | 0.161290 |
Family_Single | 0.696462 | 0.303538 |
Family_Small | 0.421233 | 0.578767 |
上面數(shù)據(jù)框的兩列分別表示各個(gè)家庭類別的死亡率和幸存率,這里只獲取幸存率:
# 獲取家庭類別的幸存率
FamilyCgDf_rate = FamilyCgDf2.iloc[:,1]
FamilyCgDf_rate
FamilyCategory
Family_Large 0.161290
Family_Single 0.303538
Family_Small 0.578767
Name: 1, dtype: float64
4.1.4 幸存率與家庭類別的可視化分析
可視化需要用到matplotlib包,先導(dǎo)入相關(guān)包:
%matplotlib inline
# 導(dǎo)入可視化包
import matplotlib.pyplot as plt
使用Python建立可視化圖表的步驟主要有:
- 創(chuàng)建畫板
- 創(chuàng)建畫紙,圖表都建立在畫紙上
- 選擇畫紙,繪制圖表
- 設(shè)置圖表參數(shù)
- 顯示圖表
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
'''
subplot()方法里面?zhèn)魅氲娜齻€(gè)數(shù)字
前兩個(gè)數(shù)字代表要生成幾行幾列的子圖矩陣,第三個(gè)數(shù)字代表選中的子圖位置
subplot(1,2,1)生成一個(gè)1行2列的子圖矩陣,當(dāng)前是第一個(gè)子圖
'''
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
FamilyCgDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向顯示
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Family')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Family and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper right')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
FamilyCgDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向顯示
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Family')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Family and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
在人數(shù)上,單身人士最多,其次是小家庭,最少的是大家庭;
在幸存率方面,人數(shù)最少的大家庭幸存率最低,小家庭的幸存率最高,其次是單身人士。
4.2 頭銜與生存率的關(guān)系
4.2.1 頭銜分組
首先定義一個(gè)函數(shù),用于從乘客姓名中獲取頭銜:
'''
定義函數(shù):從姓名中獲取頭銜
'''
def getTitle(name):
str1=name.split(',')[1] #Mr. Owen Harris
str2=str1.split('.')[0] #Mr
#strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格)
str3 = str2.strip()
return str3
利用該函數(shù)獲取每位乘客的頭銜,并匯總統(tǒng)計(jì)所有頭銜的數(shù)量:
# 存放提取后的特征
titleDf = pd.DataFrame()
# map函數(shù):對Series每個(gè)數(shù)據(jù)應(yīng)用自定義的函數(shù)計(jì)算
titleDf['Title'] = train['Name'].map(getTitle)
# 所有頭銜及其數(shù)量
titleDf['Title'].value_counts()
Mr 517
Miss 182
Mrs 125
Master 40
Dr 7
Rev 6
Major 2
Mlle 2
Col 2
Mme 1
Jonkheer 1
Sir 1
Lady 1
Capt 1
Ms 1
the Countess 1
Don 1
Name: Title, dtype: int64
由于頭銜類別過多,且有些頭銜數(shù)量很少,這里將頭銜重新歸為6大類,定義如下:
- Officer:政府官員
- Royalty:王室(皇室)
- Mr:已婚男士
- Mrs:已婚婦女
- Miss:年輕未婚女子
- Master:有技能的人/教師
然后,建立姓名中頭銜與6大類的映射關(guān)系,并用map函數(shù)完成轉(zhuǎn)換:
title_mapDict = {
"Capt": "Officer",
"Col": "Officer",
"Major": "Officer",
"Jonkheer": "Royalty",
"Don": "Royalty",
"Sir" : "Royalty",
"Dr": "Officer",
"Rev": "Officer",
"the Countess":"Royalty",
"Dona": "Royalty",
"Mme": "Mrs",
"Mlle": "Miss",
"Ms": "Mrs",
"Mr" : "Mr",
"Mrs" : "Mrs",
"Miss" : "Miss",
"Master" : "Master",
"Lady" : "Royalty"
}
# map函數(shù):對Series每個(gè)數(shù)據(jù)應(yīng)用自定義的函數(shù)計(jì)算
titleDf['Title'] = titleDf['Title'].map(title_mapDict)
將剛得到的頭銜分組添加到數(shù)據(jù)集train中:
train = pd.concat([train,titleDf],axis=1)
train.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | FamilySize | FamilyCategory | Title | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | U | S | 2 | Family_Small | Mr |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 2 | Family_Small | Mrs |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | U | S | 1 | Family_Single | Miss |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S | 2 | Family_Small | Mrs |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | U | S | 1 | Family_Single | Mr |
4.2.2 匯總統(tǒng)計(jì)不同頭銜與是否幸存的人數(shù)
TitleDf = pd.pivot_table(train,
index='Title',
columns='Survived',
values='PassengerId',
aggfunc='count')
TitleDf
Survived | 0 | 1 |
---|---|---|
Title | ||
Master | 17 | 23 |
Miss | 55 | 129 |
Mr | 436 | 81 |
Mrs | 26 | 101 |
Officer | 13 | 5 |
Royalty | 2 | 3 |
4.2.3 匯總統(tǒng)計(jì)不同頭銜的幸存率
# 匯總統(tǒng)計(jì)不同頭銜與是否幸存的比例
TitleDf2 = TitleDf.div(TitleDf.sum(axis=1),axis=0)
TitleDf2
Survived | 0 | 1 |
---|---|---|
Title | ||
Master | 0.425000 | 0.575000 |
Miss | 0.298913 | 0.701087 |
Mr | 0.843327 | 0.156673 |
Mrs | 0.204724 | 0.795276 |
Officer | 0.722222 | 0.277778 |
Royalty | 0.400000 | 0.600000 |
# 獲取不同頭銜的幸存率
TitleDf_rate = TitleDf2.iloc[:,1]
TitleDf_rate
Title
Master 0.575000
Miss 0.701087
Mr 0.156673
Mrs 0.795276
Officer 0.277778
Royalty 0.600000
Name: 1, dtype: float64
4.2.4 幸存率與頭銜的可視化分析
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
TitleDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Title')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Title and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper right')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
TitleDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Title')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Title and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
頭銜分類中人數(shù)最多的是已婚男士,未婚女士和已婚女士次之,其他頭銜的只占少數(shù);
幸存率方面,已婚男士最低,政府官員也較低,已婚女士和未婚女士的幸存率最高。
4.3 年齡與幸存率的關(guān)系
4.3.1 年齡分組
'''
年齡分組:
兒童(Children):0-13
青年(Youth):14-30
中年(Middle-aged):30-60
老年(The old):60以上
'''
# 定義年齡分組函數(shù)
def ageCut(a):
if a<=13:
return 'Children'
elif 13<a<=30:
return 'Youth'
elif 30<a<=60:
return 'Middle-aged'
else:
return 'The old'
#if 條件為真的時(shí)候返回if前面內(nèi)容,否則返回后面的內(nèi)容
train['AgeCategory'] =train['Age'].map(ageCut)
train[['AgeCategory','Age' ]].head()
AgeCategory | Age | |
---|---|---|
0 | Youth | 22.0 |
1 | Middle-aged | 38.0 |
2 | Youth | 26.0 |
3 | Middle-aged | 35.0 |
4 | Middle-aged | 35.0 |
4.3.2 匯總統(tǒng)計(jì)不同年齡段與是否幸存的人數(shù)
AgeDf = pd.pivot_table(train,
index='AgeCategory',
columns='Survived',
values='PassengerId',
aggfunc='count',
fill_value=0)
AgeDf
Survived | 0 | 1 |
---|---|---|
AgeCategory | ||
Children | 29 | 42 |
Middle-aged | 164 | 119 |
The old | 17 | 5 |
Youth | 339 | 176 |
4.3.3 匯總統(tǒng)計(jì)不同年齡段的幸存率
# 匯總統(tǒng)計(jì)不同年齡與是否幸存的比例
AgeDf2 = AgeDf.div(AgeDf.sum(axis=1),axis=0)
AgeDf2
Survived | 0 | 1 |
---|---|---|
AgeCategory | ||
Children | 0.408451 | 0.591549 |
Middle-aged | 0.579505 | 0.420495 |
The old | 0.772727 | 0.227273 |
Youth | 0.658252 | 0.341748 |
# 獲取不同年齡段的幸存率
AgeDf_rate = AgeDf2.iloc[:,1]
AgeDf_rate
AgeCategory
Children 0.591549
Middle-aged 0.420495
The old 0.227273
Youth 0.341748
Name: 1, dtype: float64
4.3.4 幸存率與年齡的可視化分析
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
AgeDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Age')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Age and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper left')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
AgeDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Age')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Age and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
青年人數(shù)最多,中年人次之,兒童人數(shù)較少,老年人最少;
兒童的幸存率最高,中年人次之,老年人的最低。
4.4 客艙等級與幸存率的關(guān)系
4.4.1 匯總統(tǒng)計(jì)不同客艙等級與是否幸存的人數(shù)
PclassDf = pd.pivot_table(train,
index='Pclass',
columns='Survived',
values='PassengerId',
aggfunc='count')
PclassDf
Survived | 0 | 1 |
---|---|---|
Pclass | ||
1 | 80 | 136 |
2 | 97 | 87 |
3 | 372 | 119 |
4.4.2 匯總統(tǒng)計(jì)不同客艙等級的幸存率
# 匯總統(tǒng)計(jì)不同客艙等級與是否幸存的比例
PclassDf2 = PclassDf.div(PclassDf.sum(axis=1),axis=0)
PclassDf2
Survived | 0 | 1 |
---|---|---|
Pclass | ||
1 | 0.370370 | 0.629630 |
2 | 0.527174 | 0.472826 |
3 | 0.757637 | 0.242363 |
# 獲取不同客艙等級的幸存率
PclassDf_rate = PclassDf2.iloc[:,1]
PclassDf_rate
Pclass
1 0.629630
2 0.472826
3 0.242363
Name: 1, dtype: float64
4.4.3 幸存率與客艙等級的可視化分析
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
PclassDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Pclass')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Pclass and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper left')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
PclassDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Pclass')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Pclass and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
三等艙的人數(shù)最多,一等艙和二等艙人數(shù)相差不多;
一等艙幸存率最高,二等艙次之,三等艙最低。
4.5 性別與幸存率的關(guān)系
4.5.1 匯總統(tǒng)計(jì)不同性別與是否幸存的人數(shù)
SexDf = pd.pivot_table(train,
index='Sex',
columns='Survived',
values='PassengerId',
aggfunc='count')
SexDf
Survived | 0 | 1 |
---|---|---|
Sex | ||
female | 81 | 233 |
male | 468 | 109 |
4.5.2 匯總統(tǒng)計(jì)不同性別的幸存率
# 匯總統(tǒng)計(jì)不同性別與是否幸存的比例
SexDf2 = SexDf.div(SexDf.sum(axis=1),axis=0)
SexDf2
Survived | 0 | 1 |
---|---|---|
Sex | ||
female | 0.257962 | 0.742038 |
male | 0.811092 | 0.188908 |
# 獲取不同性別的幸存率
SexDf_rate = SexDf2.iloc[:,1]
SexDf_rate
Sex
female 0.742038
male 0.188908
Name: 1, dtype: float64
4.5.3 幸存率與性別的可視化分析
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
SexDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Sex')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Sex and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper left')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
SexDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Sex')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Sex and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
乘客性別以男性為主,大約是女性的兩倍;
男性的幸存率比女性低很多,不及女性的三分之一。
4.6 登船港口與幸存率的關(guān)系
4.6.1 匯總統(tǒng)計(jì)不同登船港口與是否幸存的人數(shù)
EmbarkedDf = pd.pivot_table(train,
index='Embarked',
columns='Survived',
values='PassengerId',
aggfunc='count')
EmbarkedDf
Survived | 0 | 1 |
---|---|---|
Embarked | ||
C | 75 | 93 |
Q | 47 | 30 |
S | 427 | 219 |
4.6.2 匯總統(tǒng)計(jì)不同登船港口的幸存率
# 匯總統(tǒng)計(jì)不同登船港口與是否幸存的比例
EmbarkedDf2 = EmbarkedDf.div(EmbarkedDf.sum(axis=1),axis=0)
EmbarkedDf2
Survived | 0 | 1 |
---|---|---|
Embarked | ||
C | 0.446429 | 0.553571 |
Q | 0.610390 | 0.389610 |
S | 0.660991 | 0.339009 |
# 獲取不同登船港口的幸存率
EmbarkedDf_rate = EmbarkedDf2.iloc[:,1]
EmbarkedDf_rate
Embarked
C 0.553571
Q 0.389610
S 0.339009
Name: 1, dtype: float64
4.6.4 幸存率與登船港口的可視化分析
# 創(chuàng)建畫板并設(shè)置大小
fig = plt.figure(1)
plt.figure(figsize=(12,4))
# 創(chuàng)建畫紙(子圖)
#創(chuàng)建畫紙,并選擇畫紙1
ax1 = plt.subplot(1,2,1)
# 在畫紙1繪制堆積柱狀圖
EmbarkedDf.plot(ax=ax1,#選擇畫紙1
kind='bar',#選擇圖表類型
stacked=True,#是否堆積
color=['orangered','royalblue'] #設(shè)置圖表顏色
)
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Embarked')
# y坐標(biāo)軸文本
plt.ylabel('Num')
# 圖表標(biāo)題
plt.title('Embarked and Survived Num')
# 設(shè)置圖例
plt.legend(labels=['Not Survived','Survived'],loc='upper left')
# 選擇畫紙2
ax2 = plt.subplot(1,2,2)
# 在畫紙2繪制柱狀圖
EmbarkedDf_rate.plot(ax=ax2,kind='bar',color='orange')
# x坐標(biāo)軸橫向
plt.xticks(rotation=360)
# x坐標(biāo)軸文本
plt.xlabel('Embarked')
# y坐標(biāo)軸文本
plt.ylabel('Survived Rate')
# 圖表標(biāo)題
plt.title('Embarked and Survived Rate')
# 顯示圖表
plt.show()
<Figure size 432x288 with 0 Axes>
乘客絕大部分都是從Southampton登船,同時(shí)Southampton登船的乘客幸存率也最低;幸存率最高的是從Cherbourg登船的乘客。
5. 總結(jié)
5.1 家庭類別:
小家庭的幸存率最高,人數(shù)最少的大家庭反而幸存率最低。
5.2 頭銜:
已婚男士人數(shù)最多,但他們的幸存率最低,未婚女士和已婚女士人數(shù)雖然人數(shù)也多,幸存率卻最高。
5.3 年齡:
乘客以青年人為主,但兒童的幸存率最高,說明當(dāng)時(shí)逃生時(shí)兒童優(yōu)先;老年人的人數(shù)少,幸存率也低,可能是由于老人行動(dòng)不便,來不及逃生。
5.4 客艙等級:
三等艙的人數(shù)最多,但幸存率從一等艙到三等艙依次下降,票價(jià)越高,幸存率越高,說明上層階級有更大的逃生機(jī)會(huì)。
5.5 性別:
乘客性別以男性為主,大約是女性的兩倍;男性的幸存率比女性低很多,不及女性的三分之一,反映當(dāng)時(shí)逃生時(shí)女士優(yōu)先的原則。
5.6 登船港口:
從三個(gè)港口上船的乘客中,Southampton港口的最多,可能是泰坦尼克號出發(fā)港口的原因;同時(shí)Southampton港口登船的乘客幸存率最低,可能是因?yàn)閺脑摳劭诘谴某丝蛿?shù)量巨大,且身份來自不同階層;而從Cherbourg登船的乘客幸存率最高。文章來源:http://www.zghlxwxcb.cn/news/detail-500616.html
綜上,如果當(dāng)時(shí)有一個(gè)小女孩,在父母陪伴下從Cherbourg港口登船,且乘坐的是一等艙,那么她從那次海難中幸存的概率最大;反之,帶著一大家子親戚從Southampton港口登船,乘坐在三等艙的男性老人,能夠幸存的概率最小。文章來源地址http://www.zghlxwxcb.cn/news/detail-500616.html
到了這里,關(guān)于泰坦尼克號可視化數(shù)據(jù)分析報(bào)告的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!