Python Practice › SQLite Programs › Program 20

Query into pandas

EasySQLite Programs · 20 of 20

Write a Python program to load a query result into a pandas DataFrame.

Advertisement
Output
    city  total
0   Pune   2180
1  Delhi    450

Approach

  1. pd.read_sql_query(sql, conn).

Solution

Python
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.

More sqlite programs

← All 20 SQLite Programs

Leave a Comment