IndexToString
​
Symmetrically to StringIndexer, IndexToString maps a column of label indices back to a column containing the original labels as strings. A common use case is to produce indices from labels with StringIndexer, train a model with those indices and retrieve the original labels from the column of predicted indices with IndexToString. However, you are free to supply your own labels.
Examples
Building on the StringIndexer example, let’s assume we have the following DataFrame with columns id and categoryIndex:
id
categoryIndex
0
0.0
1
2.0
2
1.0
3
0.0
4
0.0
5
1.0
Applying IndexToString with categoryIndex as the input column, originalCategory as the output column, we are able to retrieve our original labels (they will be inferred from the columns’ metadata):
id
categoryIndex
originalCategory
0
0.0
a
1
2.0
b
2
1.0
c
3
0.0
a
4
0.0
a
5
1.0
c
1
import org.apache.spark.ml.attribute.Attribute
2
import org.apache.spark.ml.feature.{IndexToString, StringIndexer}
3
​
4
val df = spark.createDataFrame(Seq(
5
(0, "a"),
6
(1, "b"),
7
(2, "c"),
8
(3, "a"),
9
(4, "a"),
10
(5, "c")
11
)).toDF("id", "category")
12
​
13
val indexer = new StringIndexer()
14
.setInputCol("category")
15
.setOutputCol("categoryIndex")
16
.fit(df)
17
val indexed = indexer.transform(df)
18
​
19
println(s"Transformed string column '${indexer.getInputCol}' " +
20
s"to indexed column '${indexer.getOutputCol}'")
21
indexed.show()
22
​
23
val inputColSchema = indexed.schema(indexer.getOutputCol)
24
println(s"StringIndexer will store labels in output column metadata: " +
25
s"${Attribute.fromStructField(inputColSchema).toString}\n")
26
​
27
val converter = new IndexToString()
28
.setInputCol("categoryIndex")
29
.setOutputCol("originalCategory")
30
​
31
val converted = converter.transform(indexed)
32
​
33
println(s"Transformed indexed column '${converter.getInputCol}' back to original string " +
34
s"column '${converter.getOutputCol}' using labels in metadata")
35
converted.select("id", "categoryIndex", "originalCategory").show()
36
​
37
/*
38
Output:
39
​
40
Transformed string column 'category' to indexed column 'categoryIndex'
41
+---+--------+-------------+
42
| id|category|categoryIndex|
43
+---+--------+-------------+
44
| 0| a| 0.0|
45
| 1| b| 2.0|
46
| 2| c| 1.0|
47
| 3| a| 0.0|
48
| 4| a| 0.0|
49
| 5| c| 1.0|
50
+---+--------+-------------+
51
​
52
StringIndexer will store labels in output column metadata: {"vals":["a","c","b"],"type":"nominal","name":"categoryIndex"}
53
​
54
Transformed indexed column 'categoryIndex' back to original string column 'originalCategory' using labels in metadata
55
+---+-------------+----------------+
56
| id|categoryIndex|originalCategory|
57
+---+-------------+----------------+
58
| 0| 0.0| a|
59
| 1| 2.0| b|
60
| 2| 1.0| c|
61
| 3| 0.0| a|
62
| 4| 0.0| a|
63
| 5| 1.0| c|
64
+---+-------------+----------------+
65
​
66
*/
Copied!
Last modified 1yr ago
Copy link