Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of pyodbc.rows to pandas Dataframe takes very long time

Is there a faster way to convert pyodbc.rows object to pandas Dataframe? It take about 30-40 minutes to convert a list of 10 million+ pyodbc.rows objects to pandas dataframe.

import pyodbc
import pandas

server = <server_ip> 
database = <db_name> 
username = <db_user> 
password = <password> 
port='1443'

conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';PORT='+port+';DATABASE='+database+';UID='+username+';PWD='+ password)

#takes upto 12 minutes
rows = cursor.execute("select top 10000000 * from [LSLTGT].[MBR_DIM] ").fetchall() 

#Read cursor data into Pandas dataframe.....Takes forever!
df = pandas.DataFrame([tuple(t) for t in rows]) 
like image 388
Anjana Shivangi Avatar asked Nov 26 '18 17:11

Anjana Shivangi


Video Answer


2 Answers

You might get some improvement by using a generator expression rather than a list comprehension:

df = pandas.DataFrame((tuple(t) for t in rows)) 
like image 104
Owen Avatar answered Sep 30 '22 19:09

Owen


There is also an option to do this directly with pandas:

df = pd.DataFrame.from_records(rows, columns=[col[0] for col in cursor.description])
like image 27
ira Avatar answered Sep 30 '22 17:09

ira