如何避免在 apache spark 数据框中的列选择中进行硬编码 |斯卡拉

How to avoid hardcoding in column selection in data frame in apache spark | Scala

我有以下数据框,我需要在其上使用 spark ml 运行 逻辑回归:

uid  a  b  c  label d
1    0  1  3  0     2
2    3  0  0  1     0

在使用 ml 包时,我开始知道我需要以

格式创建数据
label  feature
0      [0,1,3,2]
1      [3,0,0,0]

现在我遇到了 VectorAssembler 来创建特征列,同时我需要做一些类似

的事情
val assembler = new VectorAssembler()
.setInputCols(Array("a", "b", "c", "d"))
.setOutputCol("features")

有没有办法避免对各个特征列名称进行硬编码

取决于你的数据。如果你知道你总是有一组特定的列不属于你的特征向量(uid 和标签)并且可以假设所有其他列都是,你可以这样做:

// df is your data frame
val assembler = new VectorAssembler()
.setInputCols(df.columns.diff(Array("uid","label")))
.setOutputCol("features")