我需要将数据集中的两行或更多行合并为一行。分组必须基于 id
列来完成。要合并的列是一个字符串。我需要在合并列中获取逗号分隔的字符串。我如何在Java中实现这一点?
输入行
col1,col2
1,abc
2,pqr
1,abc1
3,xyz
2,pqr1
预期输出:
col1, col2
1, "abc,abc1"
2, "pqr,pqr1"
3, xyz
最佳答案
聚合两个单独的列:
your_data_frame
.withColumn("aggregated_column", concat_ws(",", col("col1"), col("col2"))
为了以防万一,这里是除了常用的东西之外还需要导入的内容
import static org.apache.spark.sql.functions.*;
编辑
如果您想聚合任意数量的已知名称的列,可以这样做:
String[] column_names = {"c1", "c2", "c3"};
Column[] columns = Arrays.asList(column_names)
.stream().map(x -> col(x))
.collect(Collectors.toList())
.toArray(new Column[0]);
data_frame
.withColumn("agg", concat_ws(",", columns));
编辑#2:分组和连接
如果您想按“ID”列进行分组并聚合另一列,可以这样做:
dataframe
.groupBy("ID")
.agg(concat_ws(",", collect_list(col("col1")) ))
关于java - 如何合并 Spark 数据集中的行以合并字符串列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870827/