Exporting SQL query results to pandas dataframe

◇◆丶佛笑我妖孽 提交于 2019-12-25 06:46:20

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/43151779/exporting-sql-query-results-to-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!