-
Notifications
You must be signed in to change notification settings - Fork 820
/
SelectColumns.scala
68 lines (51 loc) · 2.32 KB
/
SelectColumns.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.
package com.microsoft.azure.synapse.ml.stages
import com.microsoft.azure.synapse.ml.codegen.Wrappable
import com.microsoft.azure.synapse.ml.logging.{FeatureNames, SynapseMLLogging}
import org.apache.spark.ml.Transformer
import org.apache.spark.ml.param._
import org.apache.spark.ml.util._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset}
object SelectColumns extends DefaultParamsReadable[SelectColumns]
/** <code>SelectColumns</code> takes a dataframe and a list of columns to select as input and returns
* a dataframe comprised of only those columns listed in the input list.
*
* The columns to be selected is a list of column names
*/
class SelectColumns(val uid: String) extends Transformer
with Wrappable with DefaultParamsWritable with SynapseMLLogging {
logClass(FeatureNames.Core)
def this() = this(Identifiable.randomUID("SelectColumns"))
val cols: StringArrayParam = new StringArrayParam(this, "cols", "Comma separated list of selected column names")
/** @group getParam */
final def getCols: Array[String] = $(cols)
/** @group setParam */
def setCols(value: Array[String]): this.type = set(cols, value)
def setCol(value: String): this.type = set(cols, Array(value))
/** @param dataset - The input dataset, to be transformed
* @return The DataFrame that results from column selection
*/
override def transform(dataset: Dataset[_]): DataFrame = {
logTransform[DataFrame]({
verifySchema(dataset.schema)
dataset.toDF().select(getCols.map(col): _*)
}, dataset.columns.length)
}
def transformSchema(schema: StructType): StructType = {
verifySchema(schema)
val selectedCols = getCols.toSet
StructType(schema.fields.filter(f => selectedCols(f.name)))
}
def copy(extra: ParamMap): SelectColumns = defaultCopy(extra)
private def verifySchema(schema: StructType): Unit = {
val providedCols = schema.fields.map(_.name).toSet
val invalidCols = getCols.filter(!providedCols(_))
if (invalidCols.length > 0) {
throw new NoSuchElementException(
s"DataFrame does not contain specified columns: ${invalidCols.reduce(_ + "," + _)}")
}
}
}