将py2neo路径解析为Pandas

2024-10-03 23:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我们使用py2neocypher查询返回{}。我们希望将结果解析为Pandas DataFramecypher查询与下面的查询类似

query='''MATCH p=allShortestPaths(p1:Type1)-[r*..3]-(p2:Type1)
WHERE p1.ID =123456
RETURN distinct(p)''
result = graph.run(query)

结果对象是一个walkable对象,可以遍历它。需要注意的是,Nodes和{}没有相同的属性。
迭代对象的最pythonic方式是什么?是否有必要处理整个路径,或者因为对象是字典,所以可以使用Pandas.from_dict方法?有时存在路径长度不相等的问题。
目前我们正在枚举该对象,如果它是一个不相等的对象,那么它就是Node,否则我们将该对象作为relationship处理。在

^{pr2}$

我们可以使用isinstance方法,即

 if isinstance(item, py2neo.types.Node ):
   #process as Node

但这仍然需要分别处理每个元素。在


Tags: 对象方法路径nodedataframepandasmatchquery
1条回答
网友
1楼 · 发布于 2024-10-03 23:21:11

我解决问题如下:
我编写了一个函数,它接收带有节点和关系属性的路径列表

def neo4j_graph_to_dict(paths, node_properties, rels_properties):   
    paths_dict=OrderedDict()
    for (pathID, path) in enumerate(paths):
        paths_dict[pathID]={}
        for (i, node_rel) in enumerate(path):
            n_properties = [node_rel[np] for np in node_properties]
            r_properties = [node_rel[rp] for rp in rels_properties]
            if isinstance(node_rel, Node):
                node_fromat = [np+': {}|'for np in node_properties]
                paths_dict[pathID]['Node'+str(i)]=('{}: '+' '.join(node_fromat)).format(list(node_rel.labels())[0], *n_properties)                
            elif isinstance(node_rel, Relationship):
                rel_fromat = [np+': {}|'for np in rels_properties]
                reltype= 'Rel'+str(i-1)
                paths_dict[pathID][reltype]= ('{}: '+' '.join(rel_fromat)).format(node_rel.type(), *r_properties)
    return paths_dict 

假设查询返回路径、节点和关系,我们可以运行以下代码:

^{pr2}$

相关问题 更多 >