14

我有一个DataFrame df五列的 Spark。我想添加另一列,其值是第一列和第二列的元组。使用 withColumn() 方法时,出现不匹配错误,因为输入不是 Column 类型,而是 (Column,Column)。我想知道在这种情况下,除了在行上运行 for 循环之外是否有解决方案?

var dfCol=(col1:Column,col2:Column)=>(col1,col2)
val vv = df.withColumn( "NewColumn", dfCol( df(df.schema.fieldNames(1)) , df(df.schema.fieldNames(2)) ) )
4

4 回答 4

29

您可以使用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]    |
+---+---+---------+
于 2017-08-04T12:01:28.247 回答
13

您可以使用用户定义的函数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))
}

用法

df.withColumn(
  "tuple_col", TupleUDFs.toTuple2[Int, Int].apply(df("a"), df("b"))
)

假设“a”和“b”是Int要放入元组的类型的列。

于 2015-09-26T17:46:58.200 回答
6

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

// $"*" will capture all existing columns
df.select($"*", array($"col1", $"col2").as("newCol")) 
于 2017-12-12T22:17:21.733 回答
2

如果要将两个数据框列合并为一列。只是:

import org.apache.spark.sql.functions.array
df.withColumn("NewColumn", array("columnA", "columnB"))
于 2019-04-14T15:31:23.493 回答