From 1c3ed2a52631f094a3a3ad7a101ea89f942946b4 Mon Sep 17 00:00:00 2001 From: Don Yin Date: Mon, 19 Aug 2024 17:52:44 +0800 Subject: [PATCH] add function - get pandas dataframe --- MetricDB/src/main.py | 29 +++++++++++++++++++++++++++++ setup.py | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/MetricDB/src/main.py b/MetricDB/src/main.py index ff99c7d..cbf8d59 100644 --- a/MetricDB/src/main.py +++ b/MetricDB/src/main.py @@ -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""" diff --git a/setup.py b/setup.py index 043d622..ccdab0c 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ setup( name="MetricDB", - version="0.0.6", + version="0.0.7", author="Don Yin", author_email="Don_Yin@outlook.com", description="A logger based on SQLite3",