From d2bbf7db75c683031a2d8a5ca91f60dc4e7a9d66 Mon Sep 17 00:00:00 2001 From: Kevin Ali Date: Tue, 14 Aug 2012 11:48:06 -0400 Subject: [PATCH] Added function to convert queryset to dataframe --- qs_to_frame.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 qs_to_frame.py diff --git a/qs_to_frame.py b/qs_to_frame.py new file mode 100644 index 0000000..bf77923 --- /dev/null +++ b/qs_to_frame.py @@ -0,0 +1,28 @@ +from django.db import DEFAULT_DB_ALIAS +from pandas.io.sql import _safe_fetch +from pandas import * + +def dataframe_from_qs(qs, database_name=DEFAULT_DB_ALIAS, coerce_float=True): + """ + """ + # Generate query, and sanitize it + sql = str(qs.query.get_compiler(database_name).as_sql()) + + # Fetch data + compiler = qs.query.get_compiler(DEFAULT_DB_ALIAS) + rows = compiler.execute_sql() + + # Fetch column names + col_count = 0 + columns = [col_desc.replace('"','').replace('.','_') for col_desc in compiler.get_columns()] + + # Generate Dataframe + df = DataFrame.from_records(rows.next(), columns=columns, coerce_float=True) + return df + + + + + + +