我有一个带有五列的Spark DataFrame
df
。我想添加另一列,其值为第一列和第二列的元组。当使用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)) ) )
您可以使用用户定义的函数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
类型的列,你想要放入一个元组。
您可以使用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] |
+---+---+---------+
您可以使用数组将多个数据框列合并为一个。
// $"*" will capture all existing columns
df.select($"*", array($"col1", $"col2").as("newCol"))
如果要将两个数据框列合并为一列。只是:
import org.apache.spark.sql.functions.array
df.withColumn("NewColumn", array("columnA", "columnB"))