【问题标题】:Need to add quotes for all in spark需要在火花中为所有人添加引号
【发布时间】:2022-08-16 06:08:19
【问题描述】:

需要在火花数据框中为所有添加引号

输入:

val someDF = Seq(
     |   (\"user1\", \"math\",\"algebra-1\",\"90\"),
     |   (\"user1\", \"physics\",\"gravity\",\"70\")
     | ).toDF(\"user_id\", \"course_id\",\"lesson_name\",\"score\")

实际输出:

+-------+---------+-----------+-----+
|user_id|course_id|lesson_name|score|
+-------+---------+-----------+-----+
|  user1|     math|  algebra-1|   90|
|  user1|  physics|    gravity|   70|
+-------+---------+-----------+-----+

预期输出:

someDF.show()

+-------+---------+-----------+-----+
|user_id|course_id|lesson_name|score|
+-------+---------+-----------+-----+
|\"user1\"|  \"math\" |\"algebra-1\"| \"90\"|
|\"user1\"|\"physics\"| \"gravity\" | \"70\"|
+-------+---------+-----------+-----+

    标签: apache-spark apache-spark-sql bigdata scala-spark


    【解决方案1】:

    您对此有两种可能性,第一种是在创建数据集时为其添加引号,例如:

    sparkSession.sparkContext.parallelize(Seq(
          ("\"user1\"", "\"math\"", "\"algebra-1\"", "\"90\""),
          ("\"user1\"", "\"physics\"", "\"gravity\"", "\"70\"")
        )).toDF("user_id", "course_id", "lesson_name", "score")
    

    这不是那么方便。第二种方法是连接所有列;首先我们得到所有列的列表:

    val cols = df1.columns
    

    然后我们遍历它们并在列值之前和之后添加引号:

    for (column <- cols) {
      df1 = df1.withColumn(column, concat(lit("\""), col(column), lit("\"")))
    }
    

    最终输出:

    +-------+---------+-----------+-----+
    |user_id|course_id|lesson_name|score|
    +-------+---------+-----------+-----+
    |"user1"|   "math"|"algebra-1"| "90"|
    |"user1"|"physics"|  "gravity"| "70"|
    +-------+---------+-----------+-----+
    

    【讨论】:

    • withColumn 不应该从循环中调用,官方文档spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/… 中提到了这一点
    • 我认为这是了解实际情况的一种简单方法。对于可扩展的应用程序,我会使用 withColumns,但我认为这个示例并非如此,因为这家伙似乎是新人。但除此之外,我完全同意不建议在生产中使用带有 Spark 的循环。
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2014-04-24
    相关资源
    最近更新 更多