SQL to pandas: the same query, clause by clause
If you already think in SQL, pandas is mostly a matter of knowing which method stands in for which clause. Each query below is shown in SQL and in pandas, with the output the pandas version really produces.
SELECT, WHERE, ORDER BY, LIMIT
The examples use two small tables: orders (order_id, customer, date, amount, status) with 8 rows, one of them cancelled, and customers (customer, country, segment) with 5 rows, one of whom never ordered.
Pick columns and filter rows
The SELECT list is a list of column names in double brackets. WHERE is a boolean mask; join conditions with & and | and wrap each in parentheses.
SQL
SELECT order_id, customer, amount
FROM orders
WHERE status = 'completed' AND amount > 100;pandas
orders.loc[(orders["status"] == "completed") & (orders["amount"] > 100), ["order_id", "customer", "amount"]]Result:
order_id customer amount
0 1 acme 120.0
1 2 birch 300.0
4 5 dune 210.0
5 6 birch 150.0
7 8 cobalt 500.0Sort and keep the top rows
ORDER BY ... DESC is sort_values(ascending=False) and LIMIT is head. nlargest does both in one call.
SQL
SELECT order_id, customer, amount
FROM orders
ORDER BY amount DESC
LIMIT 3;pandas
orders.sort_values("amount", ascending=False).head(3)[["order_id", "customer", "amount"]]Result:
order_id customer amount
7 8 cobalt 500.0
1 2 birch 300.0
4 5 dune 210.0Write it yourself: SQL WHERE, ORDER BY and LIMIT, checked on two datasets.
DISTINCT and COUNT(DISTINCT ...)
drop_duplicates gives the distinct rows; nunique counts distinct values.
SQL
SELECT DISTINCT customer FROM orders;
SELECT COUNT(DISTINCT customer) FROM orders;pandas
print(orders["customer"].nunique(), "distinct customers")
orders[["customer"]].drop_duplicates()Result:
4 distinct customers
customer
0 acme
1 birch
3 cobalt
4 duneTry it yourself
In SQL: SELECT order_id, customer, amount FROM orders WHERE status = 'completed' ORDER BY amount DESC LIMIT 3. Return the same three rows and columns in pandas, largest amount first.
orders: 12 rows, first 4 shown
| order_id | customer | date | amount | status |
|---|---|---|---|---|
| 1 | "acme" | 2024-01-05 | 120 | "completed" |
| 2 | "birch" | 2024-01-12 | 300 | "completed" |
| 3 | "acme" | 2024-01-28 | 80 | "completed" |
| 4 | "cobalt" | 2024-02-03 | 45 | "cancelled" |
Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.
GROUP BY and HAVING
pandas has no HAVING keyword and does not need one. Once the grouped result is a DataFrame, an ordinary filter on it does the same job.
Aggregate per group
groupby names the grouping column and agg names each output column with its source column and function.
SQL
SELECT customer, COUNT(*) AS orders, SUM(amount) AS total
FROM orders
GROUP BY customer;pandas
orders.groupby("customer", as_index=False).agg(orders=("order_id", "count"), total=("amount", "sum"))Result:
customer orders total
0 acme 3 260.0
1 birch 2 450.0
2 cobalt 2 545.0
3 dune 1 210.0Filter the groups
WHERE filters rows before grouping; HAVING filters the grouped result, so in pandas it is a filter applied after the aggregation.
SQL
SELECT customer, SUM(amount) AS total
FROM orders
WHERE status = 'completed'
GROUP BY customer
HAVING SUM(amount) > 300
ORDER BY total DESC;pandas
done = orders[orders["status"] == "completed"]
totals = done.groupby("customer", as_index=False).agg(total=("amount", "sum"))
totals[totals["total"] > 300].sort_values("total", ascending=False)Result:
customer total
2 cobalt 500.0
1 birch 450.0Write it yourself: SQL GROUP BY with HAVING, checked on two datasets.
CASE WHEN inside an aggregate
Turn each condition into a True/False column and sum it, or let crosstab count every combination at once.
SQL
SELECT customer,
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY customer;pandas
pd.crosstab(orders["customer"], orders["status"]).reset_index()Result:
status customer cancelled completed
0 acme 0 3
1 birch 0 2
2 cobalt 1 1
3 dune 0 1Write it yourself: SQL CASE WHEN inside a count, checked on two datasets.
Joins
merge is JOIN. The how argument picks the join type and defaults to inner, so a LEFT JOIN must be asked for.
INNER JOIN
Rows without a match on both sides are dropped.
SQL
SELECT o.order_id, o.customer, o.amount, c.country
FROM orders o
JOIN customers c ON c.customer = o.customer;pandas
orders.merge(customers, on="customer").head(3)[["order_id", "customer", "amount", "country"]]Result:
order_id customer amount country
0 1 acme 120.0 US
1 2 birch 300.0 UK
2 3 acme 80.0 USWrite it yourself: Inner merge on a shared key, checked on two datasets.
LEFT JOIN
Every row of the left table is kept; unmatched rows get NaN on the right.
SQL
SELECT c.customer, c.country, t.total
FROM customers c
LEFT JOIN (SELECT customer, SUM(amount) AS total FROM orders GROUP BY customer) t
ON t.customer = c.customer;pandas
customers.merge(orders.groupby("customer", as_index=False).agg(total=("amount", "sum")), on="customer", how="left")Result:
customer country segment total
0 acme US retail 260.0
1 birch UK wholesale 450.0
2 cobalt US retail 545.0
3 dune DE retail 210.0
4 ember UK wholesale NaNWrite it yourself: Left merge keeps every order, checked on two datasets.
Anti-join: rows with no match
The pandas form of LEFT JOIN ... WHERE right.key IS NULL, or NOT EXISTS, is a negated isin.
SQL
SELECT c.*
FROM customers c
LEFT JOIN orders o ON o.customer = c.customer
WHERE o.customer IS NULL;pandas
customers[~customers["customer"].isin(orders["customer"])]Result:
customer country segment
4 ember UK wholesaleWrite it yourself: Customers who never ordered, checked on two datasets.
Window functions
ROW_NUMBER: latest row per group
Sort, then keep the last row of each group. cumcount gives the row number itself when you need it.
SQL
SELECT customer, date, amount FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY date DESC) AS rn
FROM orders
) t WHERE rn = 1;pandas
orders.sort_values("date").groupby("customer").tail(1)[["customer", "date", "amount"]]Result:
customer date amount
4 dune 2024-02-10 210.0
5 birch 2024-02-20 150.0
6 acme 2024-03-02 60.0
7 cobalt 2024-03-15 500.0Write it yourself: SQL ROW_NUMBER: latest order per customer, checked on two datasets.
SUM() OVER: a running total
cumsum inside a groupby restarts the total for each group.
SQL
SELECT customer, date, amount,
SUM(amount) OVER (PARTITION BY customer ORDER BY date) AS running
FROM orders;pandas
o = orders.sort_values(["customer", "date"])
o.assign(running=o.groupby("customer")["amount"].cumsum())[["customer", "date", "amount", "running"]].head(5)Result:
customer date amount running
0 acme 2024-01-05 120.0 120.0
2 acme 2024-01-28 80.0 200.0
6 acme 2024-03-02 60.0 260.0
1 birch 2024-01-12 300.0 300.0
5 birch 2024-02-20 150.0 450.0LAG: compare with the previous row
shift moves a column down by one row within each group, which is LAG. diff is the shortcut for value minus previous value.
SQL
SELECT customer, date,
date - LAG(date) OVER (PARTITION BY customer ORDER BY date) AS days_since_last
FROM orders;pandas
o = orders.sort_values(["customer", "date"])
o.assign(days_since_last=o.groupby("customer")["date"].diff().dt.days)[["customer", "date", "days_since_last"]].head(5)Result:
customer date days_since_last
0 acme 2024-01-05 NaN
2 acme 2024-01-28 23.0
6 acme 2024-03-02 34.0
1 birch 2024-01-12 NaN
5 birch 2024-02-20 39.0Write it yourself: Average days between orders, checked on two datasets.
Practice these live
Each exercise runs real pandas in your browser and checks your result on the sample and on a second dataset. Your first 8 are free, with no account.
- SQL GROUP BY with HAVING
- SQL CASE WHEN inside a count
- SQL ROW_NUMBER: latest order per customer
- Customers who never ordered
- Left merge keeps every order