Skip to content

Commit

Permalink
add function - get pandas dataframe
Browse files Browse the repository at this point in the history
  • Loading branch information
Don-Yin committed Aug 19, 2024
1 parent a2c9d09 commit 1c3ed2a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions MetricDB/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,35 @@ def save_as_pandas_dataframe(self, name_table: str = "main", save_dir: Path = "d
if self.verbose:
print(f"[bold green]SQLite3[/bold green] Saved table '{name_table}' to {save_dir}")

def get_pandas_dataframe(self, name_table: str = "main"):
"""
Get the specified table as a pandas DataFrame.
Args:
name_table (str): The name of the table to get. Defaults to "main".
Returns:
pandas.DataFrame: The table data as a pandas DataFrame.
"""
cursor = self.connect.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (name_table,))

if not cursor.fetchone():
raise ValueError(f"Table '{name_table}' does not exist in the database.")

cursor.execute(f"SELECT * FROM {name_table}")
rows = cursor.fetchall()

cursor.execute(f"PRAGMA table_info({name_table})")
columns = [col[1] for col in cursor.fetchall()]
df = pandas.DataFrame(rows, columns=columns)
cursor.close()

if self.verbose:
print(f"[bold green]SQLite3[/bold green] Retrieved table '{name_table}' as pandas DataFrame")

return df

# ---- for debugging ----
def print_header(self):
"""of all existing tables in the database"""
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="MetricDB",
version="0.0.6",
version="0.0.7",
author="Don Yin",
author_email="[email protected]",
description="A logger based on SQLite3",
Expand Down

0 comments on commit 1c3ed2a

Please sign in to comment.