编程语言
首页 > 编程语言> > python – 将GraphFrames ShortestPath Map转换为PySpark中的DataFrame行

python – 将GraphFrames ShortestPath Map转换为PySpark中的DataFrame行

作者:互联网

我试图找到最有效的方法从GraphFrames函数shortestPaths获取Map输出,并将每个顶点的距离映射平铺为新DataFrame中的各个行.通过将距离列拉入字典然后从那里转换为pandas数据帧然后转换回Spark数据帧,我已经能够非常笨拙地做到这一点,但我知道必须有更好的方法.

from graphframes import *

v = sqlContext.createDataFrame([
  ("a", "Alice", 34),
  ("b", "Bob", 36),
  ("c", "Charlie", 30),
], ["id", "name", "age"])

# Create an Edge DataFrame with "src" and "dst" columns
e = sqlContext.createDataFrame([
  ("a", "b", "friend"),
  ("b", "c", "follow"),
  ("c", "b", "follow"),
], ["src", "dst", "relationship"])

# Create a GraphFrame
g = GraphFrame(v, e)

results = g.shortestPaths(landmarks=["a", "b","c"])
results.select("id","distances").show()

+---+--------------------+
| id|           distances|
+---+--------------------+
|  a|Map(a -> 0, b -> ...|
|  b| Map(b -> 0, c -> 1)|
|  c| Map(c -> 0, b -> 1)|
+---+--------------------+

我想要的是取上面的输出并平整距离,同时保持id为这样的东西:

+---+---+---------+      
| id| v | distance|
+---+---+---------+
|  a| a | 0       |
|  a| b | 1       |
|  a| c | 2       |
|  b| b | 0       |
|  b| c | 1       |
|  c| c | 0       |
|  c| b | 1       |
+---+---+---------+ 

谢谢.

解决方法:

你可以爆炸:

>>> from pyspark.sql.functions import explode
>>> results.select("id", explode("distances"))

标签:python,apache-spark,pyspark,spark-dataframe,graphframes
来源: https://codeday.me/bug/20190608/1199976.html