2016-06-18 30 views
3

我试图找到从GraphFrames函数shortestPath中获取Map输出的最有效方式,并将每个顶点的距离映射平铺到新DataFrame中的各个行中。我已经能够非常笨拙地将distance列拖到字典中,然后从那里转换成熊猫数据框,然后转换回Spark数据框,但我知道必须有更好的方法。将PyFark中的GraphFrames ShortestPath映射转换为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)| 
+---+--------------------+ 

我要的是采取上述输出和扁平的距离,同时保持IDS弄成这个样子:

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

感谢。

回答

2

您可以爆炸:

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