【问题标题】:schema error while converting Vector collection to dataframe将向量集合转换为数据框时出现架构错误
【发布时间】:2019-01-04 23:51:42
【问题描述】:

我有一个名为 values 的矢量集合,我正在尝试将其转换为数据帧

scala.collection.immutable.Vector[(String, Double)] = Vector((1,1.0), (2,2.4), (3,3.7), (4,5.0), (5,4.9))

我已经定义了一个如下的自定义架构并尝试进行转换。

val customSchema = new StructType()
    .add("A", IntegerType, true)
    .add("B", DoubleType, true)

val df = values.toDF.schema(customSchema)

这给了我一个错误提示,

error: overloaded method value apply with alternatives:
  (fieldIndex: Int)org.apache.spark.sql.types.StructField <and>
  (names: Set[String])org.apache.spark.sql.types.StructType <and>
  (name: String)org.apache.spark.sql.types.StructField
 cannot be applied to (org.apache.spark.sql.types.StructType)

我已经尝试了herehere 以及StructType documentation 描述的所有方法来创建架构。然而,所有方法都会导致相同的自定义架构,customSchema: org.apache.spark.sql.types.StructType = StructType(StructField(A,IntegerType,true), StructField(B,DoubleType,true))

toDF 方法在没有自定义模式的情况下工作得很好。但是我想强制使用自定义模式。谁能告诉我我在这里做错了什么?

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    schema 是一个属性。当您想要获取 StructTypeDataFrameDataset 时,您应该使用架构。

    val df = values.toDF
    df.schema
    //prints
    StructType(StructField(_1,IntegerType,false), StructField(_2,DoubleType,false))
    

    要将向量转换为DataFrameDataset,您可以使用spark.createDataFramespark.createDataset。这些方法是重载的,它们需要RDDJavaRDDjava.util.ListRow 和架构信息。您可以执行以下操作将您的Vector 转换为DataFrame

    val df = spark.createDataFrame(vec.toDF.rdd, customSchema)
    df.schema
    //prints
    StructType(StructField(A,IntegerType,true), StructField(B,DoubleType,true))
    

    希望对你有帮助!

    【讨论】:

    • 感谢您的澄清。这完全有道理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2020-12-10
    • 1970-01-01
    • 2015-03-05
    • 2018-09-25
    • 2014-06-16
    相关资源
    最近更新 更多