[英]Loading SQL data into iPython
I'm trying to load a database into iPython so that I can run loops over the data with Python. 我正在尝试将数据库加载到iPython中,以便可以使用Python在数据上运行循环。 So far I have the below query that will load the data, which can be printed to iPython: 到目前为止,我有以下查询将加载数据,该数据可以打印到iPython:
> sql = %sql SELECT * FROM products
> print sql
+----+--------------+---------------+-------+
| id | Product | Make | Price |
+----+--------------+---------------+-------+
| 0 | Product1 | Make1 | 5 |
| 1 | Product2 | Make2 | 1 |
| 2 | Product3 | Make2 | 8 |
However I'm having trouble imputing these results into Python. 但是我在将这些结果归入Python时遇到了麻烦。 Is there a good way to store data like this into python variables so that I can run loops over the data? 是否有一种将这样的数据存储到python变量中的好方法,以便我可以对数据进行循环?
Thanks in advance! 提前致谢!
Definitely check out the Python package Pandas. 一定要检查一下Python软件包Pandas。 You can import data from a SQL query into a Pandas dataframe with the read_sql_query function. 您可以使用read_sql_query函数将数据从SQL查询导入到Pandas数据框中。
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html
import pandas as pd
import pyodbc
cnxn = pyodbc.connect(connection_info)
sql = "SELECT * FROM TABLE"
df = pd.read_sql_query(sql, cnxn)
cnxn.close()
Then you can perform functions on columns. 然后,您可以对列执行功能。 You can even plot your data easily. 您甚至可以轻松地绘制数据。 This may be a more powerful tool than you're looking for, but if you want to do more than just loop over your data, it's worth checking out. 这可能是比您想要的功能更强大的工具,但是如果您想做的不仅仅是循环遍历数据,那么值得一试。
10 minutes to Pandas: http://pandas.pydata.org/pandas-docs/stable/10min.html 距熊猫10分钟路程: http : //pandas.pydata.org/pandas-docs/stable/10min.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.