问题描述
通过带有py2neo的Neo4j数据库上的密码查询在熊猫数据帧上获取结果非常简单,
Getting results on a pandas dataframe from a cypher query on a Neo4j database with py2neo is really straightforward, as:
>>> from pandas import DataFrame
>>> DataFrame(graph.data("MATCH (a:Person) RETURN a.name, a.born LIMIT 4"))
a.born a.name
0 1964 Keanu Reeves
1 1967 Carrie-Anne Moss
2 1961 Laurence Fishburne
3 1960 Hugo Weaving
现在,我正在尝试创建(或更好地合并)一组节点和从熊猫数据帧到具有py2neo的Neo4j数据库的关系.想象一下,我有一个像这样的数据框:
Now I am trying to create (or better MERGE) a set of nodes and relationships from a pandas dataframe into a Neo4j database with py2neo. Imagine I have a dataframe like:
LABEL1 LABEL2
p1 n1
p2 n1
p3 n2
p4 n2
其中标签是列标题,属性是值.我想为我的数据帧的每一行重现以下密码查询(以第一行为例):
where Labels are column header and properties as values. I would like to reproduce the following cypher query (for the first row as example), for every rows of my dataframe:
query="""
MATCH (a:Label1 {property:p1))
MERGE (a)-[r:R_TYPE]->(b:Label2 {property:n1))
"""
我知道我可以告诉py2neo只是graph.run(query)
,甚至可以用相同的方式运行LOAD CSV
密码脚本,但是我想知道是否可以遍历数据帧并在py2neo中逐行应用以上查询.
I know I can tell py2neo just to graph.run(query)
, or even run a LOAD CSV
cypher script in the same way, but I wonder whether I can iterate through the dataframe and apply the above query row by row WITHIN py2neo.
推荐答案
您可以使用DataFrame.iterrows()
遍历DataFrame并对每个行执行查询,并将该行中的值作为参数传递.
You can use DataFrame.iterrows()
to iterate through the DataFrame and execute a query for each row, passing in the values from the row as parameters.
for index, row in df.iterrows():
graph.run('''
MATCH (a:Label1 {property:$label1})
MERGE (a)-[r:R_TYPE]->(b:Label2 {property:$label2})
''', parameters = {'label1': row['label1'], 'label2': row['label2']})
这将每行执行一次事务.我们可以将多个查询批量处理到一个事务中,以提高性能.
That will execute one transaction per row. We can batch multiple queries into one transaction for better performance.
tx = graph.begin()
for index, row in df.iterrows():
tx.evaluate('''
MATCH (a:Label1 {property:$label1})
MERGE (a)-[r:R_TYPE]->(b:Label2 {property:$label2})
''', parameters = {'label1': row['label1'], 'label2': row['label2']})
tx.commit()
通常,我们可以在一个事务中批量处理约20k个数据库操作.
Typically we can batch ~20k database operations in a single transaction.
这篇关于Neo4j使用py2neo从pandas数据框中创建节点和关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!