Reading data from a sql database with pandas
When manipulating you data using pandas, it is sometimes useful to pull data from a database.
In this tutorial, we will see how to querry a dataframe from a sqlite table. Note than it would also work with any other sql database a long as you change the connxion to the one that suits your needs.
First let's import pandas and sqlite3
import pandas as pd
import sqlite3
from sqlite3 import Error
We want to store the table tutyfrutty in our dataframe. To do so, we will query all the elements present in the tutyfrutty TABLE with the command :
SELECT * FROM tutyfrutty
db_file = ".\\mydatabase.db"
try :
with sqlite3.connect(db_file) as conn:
df = pd.read_sql("SELECT * FROM tutyfrutty", conn)
del df["index"] #juste delete the index column that was stored in the table
except Error as e:
print(e)
df
fruit | color | kcal | |
---|---|---|---|
0 | Banana | yellow | 89 |
1 | Orange | orange | 47 |
2 | Apple | red | 52 |
3 | lemon | yellow | 15 |
4 | lime | green | 30 |
5 | plum | purple | 28 |
6 | Cranberry | red | 308 |
7 | Cranberry | red | 308 |