【问题标题】:Generate key value pairs from spark dataframe or RDD with column name present in key从 spark 数据帧或 RDD 生成键值对,键中存在列名
【发布时间】:2019-09-03 20:14:24
【问题描述】:

我有一个 spark 数据框,我需要如下所示的键值对。我特别需要键中的列名。我想使用单个映射器通道来做到这一点。

原始数据集:

预期的键值对:(Attribute_Name,Attribute_Value,Class),1

mapper单次通过后的预期结果:

预期数据集

【问题讨论】:

  • 最糟糕的格式,请将您的示例内联。
  • 可以有A4吗?

标签: scala apache-spark hadoop apache-spark-sql decision-tree


【解决方案1】:

这应该会有所帮助:

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.functions.{explode, udf, typedLit}
import org.apache.spark.sql.SparkSession

object test extends App {


  val conf: SparkConf = new SparkConf().setAppName("test").setMaster("local[*]")

  val sc: SparkContext = new SparkContext(conf)

    val spark = SparkSession
      .builder()
      .appName("test")
      .master("local[*]")
      .getOrCreate()

    import spark.implicits._

  val df = spark.read.format("csv").option("header", true).load("file:///Users/test/Desktop/file2.csv")

  val header: Seq[String] = df.columns.toSeq.map(x => x.trim)

  val df1 = df.withColumn("header", typedLit(header))

  val transform = udf((col0: String, col1: String, col2: String, col3: String, header: Seq[String]) => {
    Array(
      ((header(0), col0.trim, col3.trim),1),
      ((header(1), col1.trim, col3.trim),1),
      ((header(2), col2.trim, col3.trim),1)
    )
  })

  val df2 = df1.withColumn("transformed",transform($"A1", $" A2", $" A3", $" Class", $"header"))
    .withColumn("exploded", explode($"transformed"))
    .select($"exploded")

  df2.take(1).foreach(println)
}

输出:https://imgur.com/a/Je1M3Dx

【讨论】:

  • 非常感谢您的帮助。如果我的 A1、A2...A22 等列少于 22 列,那效果很好。但如果我有更多,它会抛出错误,说 UDF 方法的最大允许参数是 22。我尝试通过数组传递值,但它不起作用。有什么办法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2022-01-25
  • 1970-01-01
  • 2018-11-07
相关资源
最近更新 更多