我有这个dataframe,我想创建另一个类似于预期的数据。问题是,我想取同一组col_2的col_1 'a‘的值,并将它们放在不同的列中。有办法吗?
#+-----+-----+-----+-
#|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 |
+-----+-----+-----+-------+发布于 2022-07-26 12:38:05
假设您的数据集称为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_开头的列,并在dataset中重命名它们:
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|
+-----+-----+-----+-----+https://stackoverflow.com/questions/73122589
复制相似问题