我有一个数据框,其列数可变,例如 Col1、Col2、Col3。 我需要使用下面的代码将 Col1 和 Col2 组合成一列数据类型映射。
val df_converted = df.withColumn("ConvertedCols", map(lit("Col1"), col("Col1"), lit("Col2"), col("Col2")))
但是当我不知道列的编号和名称时,如何对所有列执行此操作?
最佳答案
一种方法是通过 flatMap
将 DataFrame 的列列表扩展为 Seq(lit(c1), col(c1), lit(c2), col(c2) , ...)
并应用 Spark 的 map如下图:
import org.apache.spark.sql.functions._
import spark.implicits._
val df = Seq(
("a", "b", "c", "d"),
("e", "f", "g", "h")
).toDF("c1", "c2", "c3", "c4")
val kvCols = df.columns.flatMap(c => Seq(lit(c), col(c)))
df.withColumn("ConvertedCols", map(kvCols: _*)).show(false)
// +---+---+---+---+---------------------------------------+
// |c1 |c2 |c3 |c4 |ConvertedCols |
// +---+---+---+---+---------------------------------------+
// |a |b |c |d |Map(c1 -> a, c2 -> b, c3 -> c, c4 -> d)|
// |e |f |g |h |Map(c1 -> e, c2 -> f, c3 -> g, c4 -> h)|
// +---+---+---+---+---------------------------------------+
https://stackoverflow.com/questions/54797315/