【学习笔记】读取数据集和手动处理离群点-以房价预测为例

 

  • 读取数据集大小
  • 读出大小集的样本数量和属性个数 注意这个{}和.format的用法 由于这个ID属性不需要用到 所以我们用一个变量把它保存起来 并且将原来数据集上的ID属性这一列删除(drop函数默认删除行 axis=1表示删除列 另外inplace的值默认为false 如果指定为true的话则表示直接修改并替换内存中数据的值)

#output the size of sets
print ('The size of training set before drop the id is {}'.format(df_train.shape))
print ('The size of test set before drop the id is {}'.format(df_test.shape))

train_ID=df_train['Id']
test_ID=df_test['Id']

df_train.drop(['Id'],axis=1,inplace=True)
df_test.drop(['Id'],axis=1,inplace=True)

print ('\nThe size of training set after drop the id is {}'.format(df_train.shape))
print ('The size of test set after drop the id is {}'.format(df_test.shape))
  • 处理离群点

首先画图找出离群点 调用matplotlib的subplots函数,返回fig和ax对象 通常我们只使用ax对象 用scatter函数指定x轴和y轴的数据 xlabel和ylabel则用来指明图中x轴和y轴显示的字

fig,ax=plt.subplots()
ax=plt.scatter(x=df_train['GrLivArea'],y=df_train['SalePrice'])
plt.xlabel('GrLivArea',fontsize=13)
plt.ylabel('SalePrice',fontsize=13)

【学习笔记】读取数据集和手动处理离群点-以房价预测为例_第1张图片

观察可知这两个属性大概是呈线性正相关的 所以那种GrLivArea很大而SalePrice很小的数据很明显是异常的 也就是图中右下角那两个点 所以我们要把离群点删了

#删除离群点
df_train=df_train.drop(df_train[(df_train['GrLivArea']>4000)&(df_train['SalePrice']<300000)].index)

#再检查一次
fig,ax=plt.subplots()
ax=plt.scatter(x=df_train['GrLivArea'],y=df_train['SalePrice'])
plt.xlabel('GrLivArea',fontsize=13)
plt.ylabel('SalePrice',fontsize=13)

【学习笔记】读取数据集和手动处理离群点-以房价预测为例_第2张图片

 

你可能感兴趣的:(数据挖掘,机器学习,python)