SQL to pandas DataFrame
In this tutorial, you will learn how to get the results of an SQL query into a pandas DataFrame.
TLDR solution
query_result = pd.read_sql_query ('''SELECT * FROM table_name''', conn)
df = pd.DataFrame(query_result, columns=['column_a', 'column_b', ...])
Step-by-Step Example
Suppose, you have the following fishes table in a sqlite3 database called fish_db on your desktop:
| fish_name | egg_count |
|---|---|
| salmon | 5,000 |
| pufferfish | 200 |
| shark | 2 |
You can then use the read_sql_query method to query a database, given a connection string.
The query result can then be easily loaded into a DataFrame:
import sqlite3
import pandas as pd
conn = sqlite3.connect('fish_db')
query_result = pd.read_sql_query('''SELECT * FROM fishes''', conn)
df = pd.DataFrame(query_result, columns=['fish_name', 'egg_count'])
print(df)
fish_name egg_count
0 salmon 5000
1 pufferfish 200
2 shark 2
That's it! You just learned how to load an SQL query result into a pandas DataFrame.