Kaggle:Titanic问题(1)——相关库函数操作

来源:互联网 发布:车辆维修记录软件 编辑:程序博客网 时间:2024/04/27 02:57

Kaggle:Titanic问题操作

1.pandas的read_csv函数

读取csv文件为DataFrame格式

from pandas import DataFramedata_train = pd.read_csv("Titanic/train.csv")data_train

输出结果:会自动将第一行处理为label

这里写图片描述

2.DataFrame.info()函数

DataFrame.info()可以发现一些数据信息,计算特征非空值的个数,以及数据类型·

data_train.info()

输出结果:

<class 'pandas.core.frame.DataFrame'>RangeIndex: 891 entries, 0 to 890Data columns (total 12 columns):PassengerId    891 non-null int64Survived       891 non-null int64Pclass         891 non-null int64Name           891 non-null objectSex            891 non-null objectAge            714 non-null float64SibSp          891 non-null int64Parch          891 non-null int64Ticket         891 non-null objectFare           891 non-null float64Cabin          204 non-null objectEmbarked       889 non-null objectdtypes: float64(2), int64(5), object(5)memory usage: 66.2+ KB

3.DataFrame.describe()函数

得到数值型数据的一些信息,数值数,平均值,极值,标准差

data_train.describe()

输出结果:

这里写图片描述

4.value_counts()离散型变量计数函数

对于DataFrame里的特定label可以通过value_counts()函数来统计每个种类的个数

data_train.Cabin.value_counts()

输出结果:

C23 C25 C27        4G6                 4B96 B98            4D                  3C22 C26            3E101               3F2                 3F33                3B57 B59 B63 B66    2C68                2B58 B60            2E121               2                  ..E67                2D35                2D36                2C52                2F4                 2C125               2C124               2                  ..F G63              1A6                 1D45                1D6                 1D56                1C101               1C54                1D28                1D37                1Name: Cabin, Length: 147, dtype: int64

也可以用图表输出

    fig = plt.figure()    data_train.Survived.value_counts().plot(kind='bar') #柱状图显示    plt.title('Survived situation')    plt.show()    data_train.Pclass.value_counts().plot(kind='bar')    plt.title('Passenger class')    plt.show()

输出结果:

这里写图片描述

示例:

femalehigh = data_train.Survived[data_train.Sex == 'female'][data_train.Pclass != 3].value_counts()femalehigh.plot(kind='bar', label='female highclass', color='#FA2479')plt.legend(["female/highclass"],loc='best')plt.show()

输出结果:

这里写图片描述

5.pyplot.subplot2grid()绘制子图函数

控制总的size与当前图的方位

plt.subplot2grid((2,3),(0,0)) #设置2*3的子图,该图位置在(0,0)处plt.subplot2grid((2,3),(0,1))plt.subplot2grid((2,3),(0,2))plt.subplot2grid((2,3),(1,0), colspan=2) #设置所占列宽为2pil.subplot2grid((2,3),(1,2))plt.show()

大致形状如下

这里写图片描述

6.连续型变量计数函数

data_train.Age.plot(kind='kde')plt.show()

输出结果:

这里写图片描述

同样根据DataFrame的特性,可以继续对特定类别计数

输出‘kde’密度曲线图

data_train.Age[data_train.Pclass == 1].plot(kind='kde')   data_train.Age[data_train.Pclass == 2].plot(kind='kde')data_train.Age[data_train.Pclass == 3].plot(kind='kde')plt.xlabel("Age")# plots an axis lableplt.ylabel("Density") plt.title("Passenger's age for class")plt.legend(('First', 'Second','Third'),loc='best') # sets legend for graph.plt.show()

输出结果:

这里写图片描述

7.计数两个离散变量个数,并用DataFrame的’构造函数’

Survived_0 = data_train.Pclass[data_train.Survived == 0].value_counts()#返回的是左名右值的映射Survived_1 = data_train.Pclass[data_train.Survived == 1].value_counts()Survived_0
3    3722     971     80Name: Pclass, dtype: int64
df = pd.DataFrame({'Survived':Survived_1,'Unsurvived':Survived_0}) #dataFrame图表格式
   Survived  Unsurvived1       136          802        87          973       119         372
df.plot(kind = 'bar', stacked = True)#输出图像stacked属性表示叠置

输出结果:

这里写图片描述

8.DataFrame.groupby()函数

具体每个特征每个属性计数:

g = data_train.groupby(['SibSp','Survived'])df = pd.DataFrame(g.count())

这里写图片描述

g = data_train.groupby(['SibSp','Survived','Pclass'])df = pd.DataFrame(g.count()['PassengerId']) #只计数这一个属性df

这里写图片描述

9.从DataFrame中提取部分数据

sub_df = data_train[['Age','Fare','Parch','SibSp','Pclass']]

输出结果:

           Age      Fare  Parch  SibSp  Pclass0    22.000000    7.2500      0      1       31    38.000000   71.2833      0      1       12    26.000000    7.9250      0      0       33    35.000000   53.1000      0      1       14    35.000000    8.0500      0      0       35    23.828953    8.4583      0      0       36    54.000000   51.8625      0      0       17     2.000000   21.0750      1      3       38    27.000000   11.1333      2      0       39    14.000000   30.0708      0      1       210    4.000000   16.7000      1      1       311   58.000000   26.5500      0      0       112   20.000000    8.0500      0      0       313   39.000000   31.2750      5      1       314   14.000000    7.8542      0      0       315   55.000000   16.0000      0      0       216    2.000000   29.1250      1      4       317   32.066493   13.0000      0      0       218   31.000000   18.0000      0      1       319   29.518205    7.2250      0      0       320   35.000000   26.0000      0      0       2

10.DataFrame.as_matrix()

将DataFrame类型转换为matrix类型以便用于模型fit

    known_age = age_df[age_df.Age.notnull()].as_matrix()    unknown_age = age_df[age_df.Age.isnull()].as_matrix()    y = known_age[:, 0]# y即目标年龄    X = known_age[:, 1:]# X即特征属性值`

11.DataFrame.loc用于替换属性值

用法如下

df.loc[ (df.Age.isnull()), 'Age' ] = predictedAgesdf.loc[ (df.Cabin.notnull()), 'Cabin' ] = "Yes"#小括号里的为判断语句,满足条件的属性值被替换,可以list替换list,或者都替换为一个值

12.pandas.get_dummies()归一化函数

DataFrame类型的属性每个特征分出来命名,归一化

prefix即表示命名新属性的前缀

形成一个新的DataFrame

dummies_Cabin = pd.get_dummies(data_train['Cabin'], prefix= 'Cabin')dummies_Cabin 

输出结果:

这里写图片描述

13.pandas.concat()函数合并DataFrame

把几个DataFrame按照axis=0(index)axis =1(columns)合并形成新的df

df = pd.concat([data_train, dummies_Cabin, dummies_Embarked, dummies_Sex, dummies_Pclass], axis=1)

输出结果:
这里写图片描述

14.DataFrame.drop()删去DataFrame某些属性

参数:

labels : single label or list-like

axis : int or axis name

level : int or level name, default None,For MultiIndex

inplace : bool, default False,If True, do operation inplace and return None

df.drop(['Pclass', 'Name', 'Sex', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)

15.利用sklearn中的preprocessing对连续型数据特征化scaling

各属性值之间scale差距太大,将对收敛速度造成很大影响!甚至不收敛!

所以我们将一些变化幅度较大的特征化到[-1,1]之内。

scaler.fit(),scaler.fit_transform()两个函数实现

DataFrame添加属性列的操作直接写就好,eg:df[‘Age’]

import sklearn.preprocessing as preprocessingscaler = preprocessing.StandardScaler()age_scale_param = scaler.fit(df['Age'])df['Age_scaled'] = scaler.fit_transform(df['Age'], age_scale_param)fare_scale_param = scaler.fit(df['Fare'])df['Fare_scaled'] = scaler.fit_transform(df['Fare'], fare_scale_param)df

16.利用filter()与正则表达式,从DataFrame中取出需要的属性值形成新的DataFrame

train_df = df.filter(regex='Survived|Age_.*|SibSp|Parch|Fare_.*|Cabin_.*|Embarked_.*|Sex_.*|Pclass_.*')

17.利用as_matrix()将DataFrame转换成可供numpy操作的list(矩阵)类型

train_np = train_df.as_matrix()

并完成切片化操作,形成特征矩阵X,y,用于下一步fit撸模型

y = train_np[:, 0] # y即Survival结果X = train_np[:, 1:]# X即特征属性值

18.DataFrame的构造函数创建DataFrame

result = pd.DataFrame({'PassengerId':data_test['PassengerId'].as_matrix(), 'Survived':predictions.astype(np.int32)})

输出结果:

这里写图片描述

19.DataFrame.to_csv()函数导出csv文件

result.to_csv("Titanic/logistic_regression_predictions.csv", index=False)

index表示文件是否显示index

20.sklearn的cross_validation模块

利用模块中的cross_val_score()对分类器评分

from sklearn import cross_validationcross_vallidation.cross_val_score(clf, X, y,cv=5) #5折交叉验证
输出结果:[ 0.81564246  0.81564246  0.78651685  0.78651685  0.81355932]

21.cross_validation分割数据

按照7:3的比例将训练数据分成train数据,cv数据

split_train, split_cv = cross_validation.train_test_split(df, test_size=0.3, random_state=0)
原创粉丝点击