Created
May 22, 2022 09:36
-
-
Save danielcs88/cfff5a46bc349010d69987290b13aad1 to your computer and use it in GitHub Desktop.
SQL queries within Pandas DataFrames
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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