# 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    |

```
import org.apache.spark.ml.feature.Imputer

val df = spark.createDataFrame(Seq(
  (1.0, Double.NaN),
  (2.0, Double.NaN),
  (Double.NaN, 3.0),
  (4.0, 4.0),
  (5.0, 5.0)
)).toDF("a", "b")

val imputer = new Imputer()
  .setInputCols(Array("a", "b"))
  .setOutputCols(Array("out_a", "out_b"))

val model = imputer.fit(df)
model.transform(df).show()

/*
Output:
+---+---+-----+-----+
|  a|  b|out_a|out_b|
+---+---+-----+-----+
|1.0|NaN|  1.0|  4.0|
|2.0|NaN|  2.0|  4.0|
|NaN|3.0|  3.0|  3.0|
|4.0|4.0|  4.0|  4.0|
|5.0|5.0|  5.0|  5.0|
+---+---+-----+-----+
*/
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://george-jen.gitbook.io/data-science-and-apache-spark/imputer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
