Skip to content

Instantly share code, notes, and snippets.

@gregroberts
Last active January 3, 2018 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gregroberts/017764eb1ee33a34a60ad9f225507284 to your computer and use it in GitHub Desktop.
Save gregroberts/017764eb1ee33a34a60ad9f225507284 to your computer and use it in GitHub Desktop.
A function for pandas to get results of a cypher query directly into a DataFrame
from pandas.core.api import DataFrame
from pandas.tseries.tools import to_datetime
#save me at site-packages\pandas\io\cypher.py
def read_cypher(cypher, con, index_col=None, params = {},parse_dates = None, columns= None):
'''
Run a Cypher query against the graph at con, put the results into a df
Parameters
----------
cypher : cypher query to be executed, may or may not have parameters to insert
con : a py2neo.Graph object representing a connection to the neo database
index_col : which column to use as the index, otherwise none used
params : A dictionary of parameters to pass into the cypher query (optional)
parse_dates : Assumes that the dates are held as unix timestamps,
provide a list of columns or a single string
columns : for if you want to alias column names
Returns
-------
df : a DataFrame
'''
results = con.cypher.execute(cypher, parameters = params)
resrows = [i.__dict__ for i in results]
df = DataFrame(resrows)
if columns != None:
df.columns = columns
if index_col != None:
df.set_index(index_col, inplace=True, drop = True)
if parse_dates != None:
if isinstance(parse_dates, basestring):
df[parse_dates] = to_datetime(df[parse_dates], unit = 's')
elif type(parse_dates) is list:
for col in parse_dates:
df[col] = to_datetime(df[col], unit = 's')
return df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment