Based on example from Neo4j
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
session.run("CREATE (a:Person {name:'Arthur', title:'King'})")
result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
for record in result:
print("%s %s" % (record["title"], record["name"]))
session.close()
Here result
is of datatype neo4j.v1.session.StatementResult
. How to access this data in pandas dataframe without explicitly iterating?
pd.DataFrame.from_records(result)
doesn't seem to help.
This is what I have using list comprehension
resultlist = [[record['title'], record['name']] for record in result]
pd.DataFrame.from_records(resultlist, columns=['title', 'name'])
The best I can come up with is a list comprehension similar to yours, but less verbose:
df = pd.DataFrame([r.values() for r in result], columns=result.keys())
The py2neo
package seems to be more suitable for DataFrames, as it's fairly straightforward to return a list of dictionaries. Here's the equivalent code using py2neo
:
import py2neo
# Some of these keyword arguments are unnecessary, as they are the default values.
graph = py2neo.Graph(bolt=True, host='localhost', user='neo4j', password='neo4j')
graph.run("CREATE (a:Person {name:'Arthur', title:'King'})")
query = "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title"
df = pd.DataFrame(graph.data(query))
Casting result records into dictionaries does the trick:
df = pd.DataFrame([dict(record) for record in result])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With