Skip to content

Instantly share code, notes, and snippets.

@danielcs88
Created May 22, 2022 09:36
Show Gist options
  • Select an option

  • Save danielcs88/cfff5a46bc349010d69987290b13aad1 to your computer and use it in GitHub Desktop.

Select an option

Save danielcs88/cfff5a46bc349010d69987290b13aad1 to your computer and use it in GitHub Desktop.
SQL queries within Pandas DataFrames
import re
import matplotlib.pyplot as plt
import pandas as pd
from sqlalchemy import create_engine
def sql_query(query: str) -> pd.DataFrame:
"""
Helper function to run SQL queries on in-house Pandas DataFrames
Parameters
----------
query : str
SQL query to run
Returns
-------
pd.DataFrame
DataFrame of results
"""
REGEX = r"(FROM )(\w+)"
DF_NAME = re.search(REGEX, query)[2]
DF = eval(DF_NAME)
engine = create_engine("sqlite://", echo=False)
DF.to_sql(DF_NAME, con=engine)
RESULT = pd.DataFrame(engine.execute(query).fetchall())
return RESULT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment