我有一个包含字符串列的数据框,我计划使用 spark 和 scala 将其用作 k-means 的输入。我正在使用以下方法转换数据框的字符串类型列:
val toDouble = udf[Double, String]( _.toDouble)
val analysisData = dataframe_mysql.withColumn("Event", toDouble(dataframe_mysql("event"))).withColumn("Execution", toDouble(dataframe_mysql("execution"))).withColumn("Info", toDouble(dataframe_mysql("info")))
val assembler = new VectorAssembler()
.setInputCols(Array("execution", "event", "info"))
.setOutputCol("features")
val output = assembler.transform(analysisData)
println(output.select("features", "execution").first())
当我打印 analysisData 模式时,转换是正确的。但我得到了一个异常(exception): VectorAssembler 不支持 StringType 类型
这意味着我的值仍然是字符串!如何转换值而不仅仅是模式类型?
谢谢
最佳答案
事实上,VectorAssembler Transformer 不接受字符串。所以你需要确保你的列匹配数值、 bool 值、向量类型。确保您的 udf 正在做正确的事情,并确保没有任何列具有 StringType。
要将 Spark DataFrame 中的列转换为另一种类型,请使其简单并使用 cast() DSL 函数,如下所示:
val analysisData = dataframe_mysql.withColumn("Event", dataframe_mysql("Event").cast(DoubleType))
它应该工作!
关于scala - VectorAssembler 不支持 StringType 类型的 scala spark 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37527753/