提取列值并将其作为Spark数据帧中的数组分配给另一列 [英] Extract a column value and assign it to another column as an array in Spark dataframe
本文介绍了提取列值并将其作为Spark数据帧中的数组分配给另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有以下各列的Spark数据框.
I have a Spark Dataframe with the below columns.
C1 | C2 | C3| C4
1 | 2 | 3 | S1
2 | 3 | 3 | S2
4 | 5 | 3 | S2
我想通过从C4列中获取不同的值来生成另一个C5列就像C5
I want to generate another column C5 by taking distinct values from column C4 like C5
[S1,S2]
[S1,S2]
[S1,S2]
有人可以帮助我如何使用Scala在Spark数据框中实现这一目标吗?
Can somebody help me how to achieve this in Spark data frame using Scala?
推荐答案
您可能希望收集第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]|
+---+---+---+---+--------+
这篇关于提取列值并将其作为Spark数据帧中的数组分配给另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文