赞
踩
#设置ast_node_interactivity = "all"使得可以同时输出多条语句
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#导入包
import pandas as pd
import numpy as np
#导入数据
train=pd.read_csv(r'E:\python\data\titanic\train.csv')
test=pd.read_csv(r'E:\python\data\titanic\test.csv')
print('训练集数据规模:{}'.format(train.shape))
print('测试集数据规模:{}'.format(test.shape))
训练集数据规模:(891, 12)
测试集数据规模:(418, 11)
训练数据集比测试数据集的列多一个,即Survived值。由于它是预测的生存值,所以,在测试数据集中没有。
#查看训练集信息
train.head()
test.head()
为了方便对训练数据和测试数据进行清洗,将训练数据和测试数据进行合并
#通过设置ignore_index=True参数,合并后的数据集会重新生成一个index
full=pd.concat([train,test],ignore_index=True)
full.head()
针对每一个字段做一个简单的解释:
PassengerId: 乘客ID;
Survived: 生存情况,0代表不幸遇难,1代表存活;
Pclass: 仓位等级,1为一等舱,2为二等舱,3为三等舱;
Name: 乘客姓名;
Sex: 性别;
Age: 年龄;
SibSp: 乘客在船上的兄妹姐妹数/配偶数(即同代直系亲属数);
Parch: 乘客在船上的父母数/子女数(即不同代直系亲属数);
Ticket: 船票编号;
Fare: 船票价格;
Cabin: 客舱号;
Embarked: 登船港口(S: Southampton; C: Cherbourg Q: Queenstown)
#查看数据描述性统计
full.describe()
因为,describe()函数只能查看数据类型的描述统计信息,无法查看类似字符类型的信息。
故需用info()函数进一步查看每一列的数据信息。
full.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1309 entries, 0 to 1308
Data columns (total 12 columns):
Age 1046 non-null float64
Cabin 295 non-null object
Embarked 1307 non-null object
Fare 1308 non-null float64
Name 1309 non-null object
Parch 1309 non-null int64
PassengerId 1309 non-null int64
Pclass 1309 non-null int64
Sex 1309 non-null object
SibSp 1309 non-null int64
Survived 891 non-null float64
Ticket 1309 non-null object
dtypes: float64(3), int64(4), object(5)
memory usage: 122.8+ KB

数据的总行数为1309行,其中,Age一栏中263列有缺失项;Fare一栏中1列有缺失项;Survived一栏只有891列,刚好对应训练数据集的行数。除了Age和Fare以外,Cabin/Embarked也有缺失项。
也可以用另一个命令,查看缺失项信息
full.isnull().sum()
Age 263
Cabin 1014
Embarked 2
Fare 1
Name 0
Parch 0
PassengerId 0
Pclass 0
Sex 0
SibSp 0
Survived 418
Ticket 0
dtype: int64
如果是数值类型,使用平均值或者中位数进行填充
年龄(Age) 最小值为0.17,不存在0值,其数据缺失率为263/1309=20.09%,由于Age的平均数与中位数接近,故选择平均值作为缺失项的填充值。
full['Age']=full['Age'].fillna(full['Age'].mean())
full.loc[full['Fare']==0,:]
让我们先看下那些票价不为0的数据,其不同仓位等级的票均价
full.loc[full['Fare']!=0,:].groupby('Pclass')['Fare'].mean()
Pclass
1 89.447482
2 21.648108
3 13.378473
Name: Fare, dtype: float64
full.loc[(full['Fare']==0)&(full['Pclass']==1),'Fare']=89.4
full.loc[(full['Fare']==0)&(full['Pclass']==2),'Fare']=21.6
full.loc[(full[&
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。