创建一个对值进行分组的列

时间:2016-03-11 11:35:34

标签: sql hive pyspark pyspark-sql

要恢复,我想将相关的组值放入相关的组:

这就是我所拥有的:

col1    col2
1        2
1        3
2        3
4        5
5        6

我想要这个:

col1    col2    group
1        2        1
1        3        1
2        3        1
4        5        2
5        6        2

如果我手动完成这两个组的生成步骤。

  • 第1行:1与2相关联,因此它们位于同一组中,让我们将其称为第1组
  • 第2行:1在第1组,现在1与3相关联,因此3也在第1组
  • 第3行:2在组1上,3也在第1组上,因此它们在第1组中
  • 第4行:4不是第1组的值,因此我创建了一个名为2的新组,并将其与5相关联。
  • 第5行:5有一个组2,并且与6相关联,因此它有第2组。

您是否有想在SQL中解决此问题的方法。 知道我正在使用Hive或pyspark

1 个答案:

答案 0 :(得分:1)

根据A.R.Ferguson的回答,我能够使用pyspark和graphframe找出解决方案:

from graphframes import *
vertices = sqlContext.createDataFrame([
  ("A",  1),
  ("B",  2),
  ("C",  3),
  ("D",  4),
  ("E",  5),
  ("F",  6)], ["name",  "id"])
edges = sqlContext.createDataFrame([
  (1, 2),
  (1, 3),
  (2, 3),
  (4, 5),
  (5, 6)], ["src", "dst"])
g = GraphFrame(vertices, edges)
result = g.connectedComponents()
result.show()

再次感谢弗格森。

相关问题