Apache spark 数据帧和数据集-将值转换为<;k、 v>;一对

Apache spark 数据帧和数据集-将值转换为<;k、 v>;一对,apache-spark,apache-spark-sql,apache-spark-dataset,Apache Spark,Apache Spark Sql,Apache Spark Dataset,我有一个数据帧(一个是黑色的),我怎样才能把它转换成红色的呢? (列号、值) [附图] val df = spark.read.format("csv").option("inferSchema", "true").option("header", "true").load("file:/home/hduser/Desktop/Demo.csv") case class Employee(EmpId: String, Experience: Double, Salary: Double) v

我有一个数据帧(一个是黑色的),我怎样才能把它转换成红色的呢? (列号、值)

[附图]

val df = spark.read.format("csv").option("inferSchema", "true").option("header", "true").load("file:/home/hduser/Desktop/Demo.csv")

case class Employee(EmpId: String, Experience: Double, Salary: Double)

val ds = df.as[Employee]
我需要数据帧和数据集两种方式的解决方案


先谢谢你!:-)

我相信当你说结对时,这是你想要的结构。检查下面的代码是否给出了预期的输出

使用数据帧:

import spark.sqlContext.implicits._
import org.apache.spark.sql.functions._
val data = Seq(("111",5,50000),("222",6,60000),("333",7,60000))
val df = data.toDF("EmpId","Experience","Salary")

val newdf = df.withColumn("EmpId", struct(lit("1").as("key"),col("EmpId").as("value")))
  .withColumn("Experience", struct(lit("2").as("key"),col("Experience").as("value")))
  .withColumn("Salary", struct(lit("3").as("key"),col("Salary").as("value")))
  .show(false)
输出:

+--------+----------+----------+
|EmpId   |Experience|Salary    |
+--------+----------+----------+
|[1, 111]|[2, 5]    |[3, 50000]|
|[1, 222]|[2, 6]    |[3, 60000]|
|[1, 333]|[2, 7]    |[3, 60000]|
+--------+----------+----------+
使用数据集:

首先,您需要为新结构定义case类,否则无法创建数据集

case class Employee2(EmpId: EmpData, Experience: EmpData, Salary: EmpData)
case class EmpData(key: String,value:String)

val ds = df.as[Employee]
val newDS = ds.map(rec=>{
  (EmpData("1",rec.EmpId), EmpData("2",rec.Experience.toString),EmpData("3",rec.Salary.toString))
})
val finalDS = newDS.toDF("EmpId","Experience","Salary").as[Employee2]
finalDS.show(false)
输出:

+--------+--------+------------+
|EmpId   |Experience|Salary    |
+--------+--------+------------+
|[1, 111]|[2, 5]  |[3, 50000]  |
|[1, 222]|[2, 6]  |[3, 60000]  |
|[1, 333]|[2, 7]  |[3, 60000]  |
+--------+--------+------------+
谢谢

非常感谢你,纳维!!:)是的,请告诉我在数据集的情况下如何更改列名。