且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

提取列值并将其作为Spark数据帧中的数组分配给另一列

更新时间:2022-03-14 21:51:01

您可能希望收集第4列中的不同项目,然后将它们放在列表"中,然后使用 withColumn 创建一个通过创建始终返回常量列表的 udf 来创建新列 C5 :

You might want to collect the distinct items from column 4 and put them in a List firstly, and then use withColumn to create a new column C5 by creating a udf that always return a constant list:

val uniqueVal = df.select("C4").distinct().map(x => x.getAs[String](0)).collect.toList    
def myfun: String => List[String] = _ => uniqueVal 
def myfun_udf = udf(myfun)

df.withColumn("C5", myfun_udf(col("C4"))).show

+---+---+---+---+--------+
| C1| C2| C3| C4|      C5|
+---+---+---+---+--------+
|  1|  2|  3| S1|[S2, S1]|
|  2|  3|  3| S2|[S2, S1]|
|  4|  5|  3| S2|[S2, S1]|
+---+---+---+---+--------+