SimpleImputer类提供了输入缺失值的基本策略。缺失值可以用常量值或使用缺失值所在列的统计信息(平均值、中位数或最频繁)进行填充。以下代码演示如何使用包含缺少值的列(轴0)的平均值替换缺少值。
import numpy as np
from numpy import nan as NA
imp = SimpleImputer(missing_values=NA, strategy='mean')
data = [[1, 2], [NA, 3], [7, 6]]
imp.fit(data)
输出:
SimpleImputer(copy=True, fill_value=None, missing_values=nan, strategy=‘mean’,
verbose=0)
这里SimpleImputer仅仅只是计算了每个属性的中位数的值,并将结果存储到该类的实例变量statistics_中:
imp.statistics_
输出:
array([4. , 3.66666667])
将拟合data的均值(mean)填充X
X = [[NA, 2], [6, NA], [7, 6]]
print(imp.transform(X))
输出:
[[4. 2. ]
[6. 3.66666667]
[7. 6. ]]
SimpleImputer类也支持稀疏矩阵
import scipy.sparse as sp
X = sp.csc_matrix([[1, 2], [0, -1], [8, 4]])
imp = SimpleImputer(missing_values=-1, strategy='mean')
imp.fit(X)
输出:
SimpleImputer(copy=True, fill_value=None, missing_values=-1, strategy=‘mean’,
verbose=0)
X_test = sp.csc_matrix([[-1, 2], [6, -1], [7, 6]])
print(imp.transform(X_test).toarray())
输出:
[[3. 2.]
[6. 3.]
[7. 6.]]
当使用’most_frequent’或’constant’策略时,SimpleImputer类还支持表示为字符串值或pandas分类的分类数据:
import pandas as pd
df = pd.DataFrame([["a", "x"],
[np.nan, "y"],
["a", np.nan],
["b", "y"]], dtype="category")
imp = SimpleImputer(strategy='most_frequent')
print(imp.fit_transform(df))
输出:
[[‘a’ ‘x’]
[‘a’ ‘y’]
[‘a’ ‘y’]
[‘b’ ‘y’]]