Imputer
​
The Imputer estimator completes missing values in a dataset, either using the mean or the median of the columns in which the missing values are located. The input columns should be of DoubleType or FloatType. Currently Imputer does not support categorical features and possibly creates incorrect values for columns containing categorical features. Imputer can impute custom values other than β€˜NaN’ by .setMissingValue(custom_value). For example, .setMissingValue(0) will impute all occurrences of (0).
Note all null values in the input columns are treated as missing, and so are also imputed.
Examples
Suppose a DataFrame with the columns a and b:
a
b
1.0
Double.NaN
2.0
Double.NaN
Double.NaN
3.0
4.0
4.0
5.0
5.0
In this example, Imputer will replace all occurrences of Double.NaN (the default for the missing value) with the mean (the default imputation strategy) computed from the other values in the corresponding columns. In this example, the surrogate values for columns a and b are 3.0 and 4.0 respectively. After transformation, the missing values in the output columns will be replaced by the surrogate value for the relevant column.
a
b
out_a
out_b
1.0
Double.NaN
1.0
4.0
2.0
Double.NaN
2.0
4.0
Double.NaN
3.0
3.0
3.0
4.0
4.0
4.0
4.0
5.0
5.0
5.0
5.0
1
import org.apache.spark.ml.feature.Imputer
2
​
3
val df = spark.createDataFrame(Seq(
4
(1.0, Double.NaN),
5
(2.0, Double.NaN),
6
(Double.NaN, 3.0),
7
(4.0, 4.0),
8
(5.0, 5.0)
9
)).toDF("a", "b")
10
​
11
val imputer = new Imputer()
12
.setInputCols(Array("a", "b"))
13
.setOutputCols(Array("out_a", "out_b"))
14
​
15
val model = imputer.fit(df)
16
model.transform(df).show()
17
​
18
/*
19
Output:
20
+---+---+-----+-----+
21
| a| b|out_a|out_b|
22
+---+---+-----+-----+
23
|1.0|NaN| 1.0| 4.0|
24
|2.0|NaN| 2.0| 4.0|
25
|NaN|3.0| 3.0| 3.0|
26
|4.0|4.0| 4.0| 4.0|
27
|5.0|5.0| 5.0| 5.0|
28
+---+---+-----+-----+
29
*/
Copied!
Last modified 1yr ago
Copy link