如何将Spark中`Dataframe`的两列合并为一个2-Tuple?

TNM*_*TNM 9 scala apache-spark-sql spark-dataframe

我有一个DataFrame df有五列的Spark .我想添加另一列,其值为第一列和第二列的元组.当使用withColumn()方法时,我得到不匹配错误,因为输入不是列类型,而是(列,列).我想知道在这种情况下是否有一个解决方案旁边的行循环运行?

var dfCol=(col1:Column,col2:Column)=>(col1,col2)
val vv = df.withColumn( "NewColumn", dfCol( df(df.schema.fieldNames(1)) , df(df.schema.fieldNames(2)) ) )
Run Code Online (Sandbox Code Playgroud)

Tau*_*das 18

您可以使用struct创建提供列的元组的函数:

import org.apache.spark.sql.functions.struct

val df = Seq((1,2), (3,4), (5,3)).toDF("a", "b")
df.withColumn("NewColumn", struct(df("a"), df("b")).show(false)

+---+---+---------+
|a  |b  |NewColumn|
+---+---+---------+
|1  |2  |[1,2]    |
|3  |4  |[3,4]    |
|5  |3  |[5,3]    |
+---+---+---------+
Run Code Online (Sandbox Code Playgroud)


Mar*_*nne 11

您可以使用用户定义的函数udf来实现您想要的功能.

UDF定义

object TupleUDFs {
  import org.apache.spark.sql.functions.udf      
  // type tag is required, as we have a generic udf
  import scala.reflect.runtime.universe.{TypeTag, typeTag}

  def toTuple2[S: TypeTag, T: TypeTag] = 
    udf[(S, T), S, T]((x: S, y: T) => (x, y))
}
Run Code Online (Sandbox Code Playgroud)

用法

df.withColumn(
  "tuple_col", TupleUDFs.toTuple2[Int, Int].apply(df("a"), df("b"))
)
Run Code Online (Sandbox Code Playgroud)

假设"a"和"b"是Int要放入元组的类型列.


Abu*_*oeb 6

您可以使用数组将多个数据框列合并为一列。

// $"*" will capture all existing columns
df.select($"*", array($"col1", $"col2").as("newCol")) 
Run Code Online (Sandbox Code Playgroud)