spark中元组到矩阵的转换

gojuced7  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(335)

我有一个rdd的元组和值列表,看起来像这样。有成千上万种不同的配对。

(A, B), 1
(B, C), 2
(C, D), 1
(A, D), 1
(D, A), 5

我想把元组值对转换成一个对应于元组值对的矩阵。我在spark里没看到什么简单的方法。

+---+------+------+------+------+
|   |  A   |  B   |  C   |  D   |
+---+------+------+------+------+
| A | -    | 1    | NULL | 1    |
| B | NULL | -    | 2    | NULL |
| C | NULL |      | -    | 1    |
| D | 5    | NULL | NULL | -    |
+---+------+------+------+------+
2ledvvac

2ledvvac1#

尽最大努力,但无法使用sparksql(您声明的)除去列名。只是以自然的顺序旋转。试试看,添加了额外的元组。

import org.apache.spark.sql.functions._ 
// Note sure what difference is between ("A", "B"), 1 or "A", "B", 1
val rdd = sc.parallelize(Seq(  (("A", "B"), 1), (("B", "C"), 2), (("C", "D"), 1), (("A", "D"), 1), (("D", "A"), 5), (("E", "Z"), 500) ))

// Can start from here in fact
val rdd2 = rdd.map(x => (x._1._1, x._1._2, x._2))

val df = rdd2.toDF()

// Natural ordering, but cannot get rid of _1 column in a DF (spark sql)
df.groupBy("_1").pivot("_2").agg(first("_3"))
  .orderBy("_1")
  .show(false)

退货:

+---+----+----+----+----+----+
|_1 |A   |B   |C   |D   |Z   |
+---+----+----+----+----+----+
|A  |null|1   |null|1   |null|
|B  |null|null|2   |null|null|
|C  |null|null|null|1   |null|
|D  |5   |null|null|null|null|
|E  |null|null|null|null|500 |
+---+----+----+----+----+----+

相关问题