我有这个数据帧,我想创建另一个类似预期的数据帧。问题是,我想取col_1的同一组"a"的col_2的值,并将它们放在不同列的同一行中。有办法做到吗?
#+-----+-----+-----+-
#|col_1| id |col_2|
#+-----+-----+-----+
#| a| 1| c|
#| a| 2| f|
#| a| 3| i|
#+-----+-----+-----+
预期
#+-----+-----+-----+-------+
#|col_1|col_c|col_f| col_i |
#+-----+-----+-----+-------+
#| a| c | f | i |
+-----+-----+-----+-------+
假设您的数据集名为main
。我们可以使用以下查询将值提取为列:
var created = main.groupBy("col_1").pivot("col_2").agg(first(col("col_2")))
这就产生了这样的输出(这几乎是你喜欢的(:
+-----+---+---+---+
|col_1| c| f| i|
+-----+---+---+---+
| a| c| f| i|
+-----+---+---+---+
现在,我们找到不以col_
开头的列,并在数据集中重命名它们:
val columns = created.columns.filterNot(c => c.startsWith("col_"))
for (i <- columns) {
created = created.withColumnRenamed(i, "col_" + i)
}
最终输出:
+-----+-----+-----+-----+
|col_1|col_c|col_f|col_i|
+-----+-----+-----+-----+
| a| c| f| i|
+-----+-----+-----+-----+