一、读入titanic.xlsx文件,按照教材示例步骤,完成数据清洗。
titanic数据集包含11个特征,分别是:
Survived:0代表死亡,1代表存活
Pclass:乘客所持票类,有三种值(1,2,3)
Name:乘客姓名
Sex:乘客性别
Age:乘客年龄(有缺失)
SibSp:乘客兄弟姐妹/配偶的个数(整数值)
Parch:乘客父母/孩子的个数(整数值)
Ticket:票号(字符串)
Fare:乘客所持票的价格(浮点数,0-500不等)
Cabin:乘客所在船舱(有缺失)
Embark:乘客登船港口:S、C、Q(有缺失)
import pandas as pd titanic=pd.DataFrame(pd.read_excel('C:\\Users\\YoungLouis\\Desktop\\python\\titanic.xlsx')) titanic.head()
titanic.drop('embark_town',axis=1,inplace=True) titanic.head()
titanic=titanic.drop_duplicates()
titanic.head()
titanic['who'].isnull().value_counts()
titanic['who']=titanic['who'].fillna('man') titanic.head()
titanic['age']=titanic['age'].fillna(titanic['age'].mean()) titanic.head()
titanic.describe()
titanic.replace([512.329200],titanic['fare'].mean())
survived = titanic['survived'].value_counts() print("乘客存活人数为:{}\n乘客死亡的人数为:{}".format(survived[1],survived[0]))
sex = titanic['sex'].value_counts() print("男性人数为:{}\n女性人数为:{}".format(sex[0],sex[1]))
female,male=0,0 for i in titanic.index: #循环统计在存活的人数中男女的个数 if titanic['survived'][i] == 1: if titanic['sex'][i] == "male": male += 1 if titanic['sex'][i] == "female": female += 1 print("存活中男性有{}人,女性有{}人".format(male,female))
pclass = titanic['pclass'].value_counts() print("乘客所在的船舱等级为1的人数:{}\n乘客所在的船舱等级为2的人数:{}\n乘客所在的船舱等级为3的人数:{}".format(pclass[1],pclass[2],pclass[3]))
print("舱位的高低和存活率的相关性为",titanic[u'survived'].corr(titanic[u'pclass']))
import pandas as pd import numpy as np import matplotlib.pyplot as plt T1 = titanic.fare[titanic.pclass == 1] T2 = titanic.fare[titanic.pclass == 2] T3 = titanic.fare[titanic.pclass == 3] plt.boxplot((T1,T2,T3)) plt.ylim(0,200) plt.show()