user308827
user308827

Reputation: 21961

Exporting SQL query results to pandas dataframe

id    date       temp       prcp
1   2015-01-01  -27.18      0
1   2015-01-02  -25.9       1.03
1   2015-01-03  -17.89      9.44
1   2015-01-04  -17.89      9.44
1   2015-01-05  -17.89      9.44

import dataset
import pandas as pd

db = dataset.connect(path_to_database_on_AWS)
res = db.query(SELECT * FROM tbl WHERE id=1 and date >= '2015-01-03' and date <= '2015-01-05')
pd.read_sql(res, con=db)

In the above code, I am using the query method from the python dataset library to read in from a table and then want to export the results as a pandas dataframe, however, I get this bug:

*** AttributeError: 'Database' object has no attribute 'cursor'

How do I export query results to pandas dataframe?

Upvotes: 0

Views: 5650

Answers (1)

MoQ93
MoQ93

Reputation: 341

You could do something like this:

   import sqlite3
   import pandas as pd
   con = sqlite3.connect('path_to_your_sql')
   myFrames = pd.read_sql_query('your query', con)

Edit: for non sqlite db you could use this for the connection:

from sqlalchemy import create_engine
con = create_engine('dialect+driver://username:password@host:port/database')

docs for create_engine

Upvotes: 1

Related Questions