我正在尝试找到从GraphFrames函数短路路径输出的最有效方法,并将每个顶点的距离映射到新的DataFrame中的单个行中。我能够通过将距离列拉到字典中,然后从那里转换为pandas dataframe,然后转换回火花数据框,但我知道必须有更好的方法。
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"))