[Scikit-Learn] - 数据预处理 - 缺失值(Missing Value)处理

reference : http://www.cnblogs.com/chaosimple/p/4153158.htmlhtml

关于缺失值(missing value)的处理

在sklearn的preprocessing包中包含了对数据集中缺失值的处理,主要是应用Imputer类进行处理。python

首先须要说明的是,numpy的数组中可使用np.nan/np.NaN(Not A Number)来代替缺失值,对于数组中是否存在nan可使用np.isnan()来断定。数组

使用type(np.nan)或者type(np.NaN)能够发现改值其实属于float类型,代码以下:编码

1
2
3
4
5
6
7
8
>>> type (np.NaN)
< type  'float' >
>>> type (np.nan)
< type  'float' >
>>> np.NaN
nan
>>> np.nan
nan

所以,若是要进行处理的数据集中包含缺失值通常步骤以下:spa

一、使用字符串'nan'来代替数据集中的缺失值;code

二、将该数据集转换为浮点型即可以获得包含np.nan的数据集;orm

三、使用sklearn.preprocessing.Imputer类来处理使用np.nan对缺失值进行编码过的数据集。htm

 

代码以下: 对象

1
2
3
4
5
6
7
8
9
10
>>> from  sklearn.preprocessing import  Imputer
>>> imp =  Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0 )
>>> X = np.array([[ 1 , 2 ], [np.nan, 3 ], [ 7 , 6 ]])
>>> Y = [[np.nan, 2 ], [ 6 , np.nan], [ 7 , 6 ]]
>>> imp.fit(X)
Imputer(axis = 0 , copy = True , missing_values = 'NaN' , strategy = 'mean' , verbose = 0 )
>>> imp.transform(Y)
array([[ 4.         2.         ],
        [ 6.         3.66666667 ],
        [ 7.         6.         ]])


上述代码使用数组X去“训练”一个Imputer类,而后用该类的对象去处理数组Y中的缺失值,缺失值的处理方式是使用X中的均值(axis=0表示按列进行)代替Y中的缺失值。blog

固然也可使用imp对象来对X数组自己进行处理。

一般,咱们的数据都保存在文件中,也不必定都是Numpy数组生成的,所以缺失值可能不必定是使用nan来编码的,对于这种状况能够参考如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
>>> line = '1,?'
>>> line = line.replace( ',?' , ',nan' )
>>> line
'1,nan'
>>> Z = line.split( ',' )
>>> Z
[ '1' , 'nan' ]
>>> Z = np.array(Z,dtype = float )
>>> Z
array([  1. ,  nan])
>>> imp.transform(Z)
array([[ 1.         3.66666667 ]])

上述代码line模拟从文件中读取出来的一行数据,使用nan来代替原始数据中的缺失值编码,将其转换为浮点型,而后使用X中的均值填补Z中的缺失值。