代码之家  ›  专栏  ›  技术社区  ›  ScalaBoy

如何创建DataFrame:列数不匹配

  •  0
  • ScalaBoy  · 技术社区  · 6 年前

    我得到一个错误:

    java.lang.IllegalArgumentException:请求失败:请求数 名称(1):'srcId'、'srcLabel'、'dstId'、'dstLabel'

    val columnNames = """'srcId', 'srcLabel', 'dstId', 'dstLabel'"""
    
    import spark.sqlContext.implicits._
    
    var df = Seq.empty[(String, String, String, String)]
      .toDF(columnNames)
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Terry Dactyl    6 年前
    scala> val columnNames = Seq("srcId", "srcLabel", "dstId", "dstLabel")
    columnNames: Seq[String] = List(srcId, srcLabel, dstId, dstLabel)
    
    scala> var d = Seq.empty[(String, String, String, String)].toDF(columnNames: _*)
    d: org.apache.spark.sql.DataFrame = [srcId: string, srcLabel: string ... 2 more fields]
    
        2
  •  3
  •   Ramesh Maharjan    6 年前

    你的方法的问题是 columnNames 是一个字符串 tuple4 空字符串。所以你必须 分裂 这个 列名 串成四串,传给 toDF

    正确的方法如下

    val columnNames = """'srcId', 'srcLabel', 'dstId', 'dstLabel'"""
    
    var df = Seq.empty[(String, String, String, String)]
      .toDF(columnNames.split(","): _*)
    

    它会给你一个空的数据帧

    +-------+-----------+--------+-----------+
    |'srcId'| 'srcLabel'| 'dstId'| 'dstLabel'|
    +-------+-----------+--------+-----------+
    +-------+-----------+--------+-----------+
    

    我希望答案是有帮助的