【问题标题】:VectorAssembler does not support the StringType type scala spark convertVectorAssembler 不支持 StringType 类型 scala spark convert
【发布时间】:2016-09-28 09:45:48
【问题描述】:

我有一个包含字符串列的数据框,我计划使用 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 模式时,转换是正确的。但我遇到了一个异常:VectorAssembler 不支持 StringType 类型 这意味着我的价值观仍然是字符串!如何转换值而不仅仅是架构类型?

谢谢

【问题讨论】:

    标签: scala vector apache-spark types


    【解决方案1】:

    确实,VectorAssembler Transformer 不接受字符串。所以你需要确保你的列匹配数字、布尔、向量类型。确保您的 udf 正在做正确的事情,并确保没有任何列具有 StringType。

    要将 Spark DataFrame 中的列转换为另一种类型,请简化并使用 cast() DSL 函数,如下所示:

    val analysisData  = dataframe_mysql.withColumn("Event", dataframe_mysql("Event").cast(DoubleType))
    

    应该可以了!

    【讨论】:

    • 如果不是只有 1 列或几列,而是说 50 或 100 或 300 列需要转换为浮点数,你会怎么做?
    • 嘿@EvanZamir,你可以试试df.selectExpr("cast(col1 as float) col1", "cast(col2 as float) col2")
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多