Python Practice › SQLite Programs › Program 20
Query into pandas
Write a Python program to load a query result into a pandas DataFrame.
Output
city total 0 Pune 2180 1 Delhi 450
Approach
pd.read_sql_query(sql, conn).
Solution
import sqlite3import pandas as pd conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE sales (city TEXT, amount INTEGER)")conn.executemany("INSERT INTO sales VALUES (?, ?)", [("Pune", 1200), ("Delhi", 450), ("Pune", 980)])df = pd.read_sql_query("SELECT city, SUM(amount) AS total FROM sales GROUP BY city ORDER BY total DESC", conn)print(df)Output
city total 0 Pune 2180 1 Delhi 450
Learn the concept
New to this topic? Read the lesson, then come back.