就个人而言,我什至不会为此使用 Pipeline API,一个array
函数就足够了
val df = sqlContext.createDataFrame(Seq((0.0, 1.0, 2.0), (3.0, 4.0, 5.0)))
.toDF("colx", "coly", "colz")
.withColumn("ft", array('colx, 'coly, 'colz))
val hashIt = new HashingTF().setInputCol("ft").setOutputCol("ft2")
val res = hashIt.transform(df)
res.show(false)
# +----+----+----+---------------+------------------------------+
# |colx|coly|colz|ft |ft2 |
# +----+----+----+---------------+------------------------------+
# |0.0 |1.0 |2.0 |[0.0, 1.0, 2.0]|(262144,[0,1,2],[1.0,1.0,1.0])|
# |3.0 |4.0 |5.0 |[3.0, 4.0, 5.0]|(262144,[3,4,5],[1.0,1.0,1.0])|
# +----+----+----+---------------+------------------------------+
作为问题的后续,为了在列数 > 3 的情况下推广数组函数的应用,以下步骤将所有列连接成一列,其中包含所有需要的列的数组:
val df2 = sqlContext.createDataFrame(Seq((0.0, 1.0, 2.0), (3.0, 4.0, 5.0)))
.toDF("colx", "coly", "colz")
val cols = (for (i <- df2.columns) yield df2(i)).toList
df2.withColumn("ft",array(cols :_*)).show
# +----+----+----+---------------+
# |colx|coly|colz| ft|
# +----+----+----+---------------+
# | 0.0| 1.0| 2.0|[0.0, 1.0, 2.0]|
# | 3.0| 4.0| 5.0|[3.0, 4.0, 5.0]|
# +----+----+----+---------------+