1

I'm trying to load a database into iPython so that I can run loops over the data with Python. So far I have the below query that will load the data, which can be printed to 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. Is there a good way to store data like this into python variables so that I can run loops over the data?

Thanks in advance!

2 Answers 2

1

Check examples here:

You can do sql[ROW][COLUMN], sql[0][1] will return Product1. If you iterate over sql it will iterate over rows.

Sign up to request clarification or add additional context in comments.

Comments

1

Definitely check out the Python package Pandas. You can import data from a SQL query into a Pandas dataframe with the read_sql_query function.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.