pandas cheat sheet: loc vs iloc, filtering, groupby, merge and pivot tables, plus the sql you already know
Stacks · 12 min read · posted Nov 30, 2026, 4:15 pm
Most of the pandas you write day to day comes down to five things: picking rows and columns with loc and iloc, filtering, groupby, merge, and pivot tables. If you know SQL, you already know what each of them does. What's left is how pandas spells it.
This is the cheat sheet from the reel. For each of the five you get when you'd reach for it, the code on a tiny table with what it printed, the mistake that usually bites, and a few things to practise on, with answers. There's a quick lookup table first, then a table that turns the SQL you know into pandas. If you came here from the SQL cheat sheet, that table is the place to start.
Every block here was run with pandas 3.1.1 (numpy 2.5.5, Python 3.14), and the output under it is what it printed. The same blocks print the same tables on pandas 2.3.3. Two of the error messages are worded differently there, and a text column's dtype shows as object instead of str. Each section starts with import pandas as pd and builds its own small table, so you can paste any one section into a file and run it.
the quick lookup
| i want to ... | write |
|---|---|
| one value, by row label and column name | df.loc[2, "name"] |
| one value, by position | df.iloc[2, 0] |
| the first 3 rows | df.head(3) |
| some of the columns | df[["name", "age"]] |
| rows where something is true | df[df["age"] > 30] |
| two conditions, both true | df[(df["age"] > 30) & (df["city"] == "Oslo")] |
| either condition | df[(df["age"] < 20) | (df["city"] == "Rome")] |
| rows whose value is in a list | df[df["city"].isin(["Oslo", "Rome"])] |
| change values on the matching rows | df.loc[df["age"] > 30, "group"] = "older" |
| a total per group | df.groupby("city")["qty"].sum() |
| several numbers per group | df.groupby("city").agg(total=("qty", "sum"), orders=("qty", "size")) |
| how many rows per group | df.groupby("city").size() |
| join two tables | orders.merge(users, on="user_id") |
| keep every row of the left table | orders.merge(users, on="user_id", how="left") |
| long rows into a grid | df.pivot_table(index="city", columns="qtr", values="sales", aggfunc="sum") |
| a grid back into long rows | wide.reset_index().melt(id_vars="city", value_name="sales") |
| sort, biggest first | df.sort_values("age", ascending=False) |
| number the rows 0, 1, 2 again | df.reset_index(drop=True) |
the sql you know, in pandas
The SQL runs on a table called people, and the pandas on a DataFrame called people with the same rows. The joins use the orders and users tables from section 4.
| name | city | age |
|---|---|---|
| Ana | Oslo | 31 |
| Ben | Rome | 37 |
| Cy | Oslo | 42 |
| Di | Oslo | 19 |
| Eve | Rome | 25 |
| sql | pandas |
|---|---|
SELECT name, age FROM people |
people[["name", "age"]] |
SELECT * FROM people WHERE age > 30 |
people[people["age"] > 30] |
WHERE age > 30 AND city = 'Oslo' |
people[(people["age"] > 30) & (people["city"] == "Oslo")] |
WHERE age < 20 OR city = 'Rome' |
people[(people["age"] < 20) | (people["city"] == "Rome")] |
WHERE city IN ('Oslo', 'Lima') |
people[people["city"].isin(["Oslo", "Lima"])] |
SELECT city, COUNT(*) FROM people GROUP BY city |
people.groupby("city").size() |
SELECT city, AVG(age) FROM people GROUP BY city |
people.groupby("city")["age"].mean() |
... GROUP BY city HAVING COUNT(*) > 2 |
n = people.groupby("city").size(), then n[n > 2] |
SELECT * FROM orders JOIN users ON users.user_id = orders.user_id |
orders.merge(users, on="user_id") |
... LEFT JOIN users ON ... |
orders.merge(users, on="user_id", how="left") |
SELECT * FROM people ORDER BY age DESC |
people.sort_values("age", ascending=False) |
... ORDER BY age DESC LIMIT 2 |
people.sort_values("age", ascending=False).head(2) |
SELECT DISTINCT city FROM people |
people["city"].drop_duplicates() |
Each row was checked: the SQL ran in SQLite, the pandas ran in pandas, and both gave back the same rows with the same values.
A few things don't carry over one for one:
- SQL's
=is==in pandas, and AND, OR and NOT are&,|and~. Each condition needs its own brackets (section 2 shows why). - SQL hands back plain rows. pandas keeps an index, the labels down the left. After a groupby the group key becomes the index, and after a filter the rows keep their old labels (sections 1 and 3).
- A missing value is NULL in SQL and NaN in pandas. A left join that finds nothing fills in NaN, and a column of whole numbers with a NaN in it turns into floats (section 4).
- SQL only promises an order when you write ORDER BY. pandas keeps rows in the order they're in, and
groupbysorts the groups by key unless you passsort=False.
1. loc vs iloc
When you reach for it. You want particular rows or columns, or one value. loc picks by label: the index label of the row and the name of the column. iloc picks by position: 0 for the first row or column, 1 for the next.
The idea. Every row has a label, shown down the left when you print a DataFrame. A new DataFrame labels its rows 0, 1, 2, so labels and positions match and it doesn't seem to matter which you use. Sort or filter it and the labels go with their rows. From then on, label 2 and position 2 are different rows.
The code. This is the table from the reel, sorted by age.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Di"],
"age": [31, 25, 42, 28],
})
df = df.sort_values("age")
print(df)
name age
1 Ben 25
3 Di 28
0 Ana 31
2 Cy 42
The labels now read 1, 3, 0, 2 from the top. The positions are still 0, 1, 2, 3.
print(df.loc[2, "name"])
print(df.iloc[2, 0])
Cy
Ana
loc found the row labelled 2, which is Cy at the bottom. iloc counted three rows down to Ana. Column 0 is name.
Slices behave differently too. A loc slice includes its end label. An iloc slice stops before its end position, the way Python lists do.
print(df.loc[3:0])
print(df.iloc[1:3])
name age
3 Di 28
0 Ana 31
name age
3 Di 28
0 Ana 31
Same two rows. loc[3:0] runs from label 3 to label 0 in the order the rows are in now, including 0. iloc[1:3] takes positions 1 and 2.
loc also takes a True/False mask for the rows (more in section 2) and a list of columns:
print(df.loc[df["age"] > 30, ["name", "age"]])
name age
0 Ana 31
2 Cy 42
What bites. Plain square brackets with a number. df[2] looks for a column called 2, not a row:
df[2]
KeyError: 2
The other one is setting values. df[df["age"] > 30]["age"] = 0 looks like it should change those ages, but it changes a copy and df stays as it was. pandas 3 warns with ChainedAssignmentError and pandas 2 with SettingWithCopyWarning. Do it in one loc:
df.loc[df["age"] > 30, "group"] = "older"
print(df)
name age group
1 Ben 25 NaN
3 Di 28 NaN
0 Ana 31 older
2 Cy 42 older
Rows that didn't match get NaN in the new column. If you'd rather have labels that match positions again, for example after a sort, renumber them. drop=True throws the old labels away instead of keeping them as a column.
df = df.reset_index(drop=True)
print(df)
print(df.loc[2, "name"], df.iloc[2, 0])
name age group
0 Ben 25 NaN
1 Di 28 NaN
2 Ana 31 older
3 Cy 42 older
Ana Ana
Practise. Start from the sorted table at the top of this section.
- What do
df.loc[0, "age"]anddf.iloc[0, 1]give? (31 and 25. Label 0 is Ana. Position 0 is Ben.) - Get the last row, whatever its label. (
df.iloc[-1], which is Cy.) - Get the names of the rows labelled 1 and 3. (
df.loc[[1, 3], "name"], which is Ben and Di.)
2. filtering
When you reach for it. You want only the rows where something is true: orders above some quantity, users in one city, rows with a missing value.
The idea. A comparison on a column doesn't give you one True or False. It gives you a whole column of them, one per row, called a mask. Put a mask in square brackets and you get the rows where it's True.
The code.
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Di"],
"city": ["Oslo", "Rome", "Oslo", "Oslo"],
"age": [31, 37, 42, 19],
})
old = df["age"] > 30
print(old)
0 True
1 True
2 True
3 False
Name: age, dtype: bool
oslo = df["city"] == "Oslo"
print(df[old & oslo])
name city age
0 Ana Oslo 31
2 Cy Oslo 42
This is the one in the reel. & is True only where both masks are. The two rows kept their labels, 0 and 2.
| is or, and ~ flips a mask:
print(df[(df["age"] < 20) | (df["city"] == "Rome")])
print(df[~oslo])
name city age
1 Ben Rome 37
3 Di Oslo 19
name city age
1 Ben Rome 37
A few shortcuts that save writing out long conditions:
print(df[df["city"].isin(["Rome", "Lima"])])
print(df[df["age"].between(30, 40)])
print(df.query("age > 30 and city == 'Oslo'"))
name city age
1 Ben Rome 37
name city age
0 Ana Oslo 31
1 Ben Rome 37
name city age
0 Ana Oslo 31
2 Cy Oslo 42
between includes both ends. query takes the condition as a string, and inside it you can write and and or.
What bites. Leaving out the brackets. & binds tighter than > and ==, so Python reads this as df["age"] > (30 & df["city"]) == "Oslo":
df[df["age"] > 30 & df["city"] == "Oslo"]
TypeError: unsupported operand type(s) for &: 'int' and 'StringArray'
Put each condition in its own brackets. The other one is writing and instead of &. and wants a single True or False, and a column of them isn't one:
df[(df["age"] > 30) and (df["city"] == "Oslo")]
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().
Practise.
- People under 40 who aren't in Oslo. (
df[(df["age"] < 40) & (df["city"] != "Oslo")], which is Ben.) - How many people are over 30? (
(df["age"] > 30).sum(), which is 3. True counts as 1.) - The names of everyone in Oslo, as a list. (
df.loc[df["city"] == "Oslo", "name"].tolist(), which is['Ana', 'Cy', 'Di'].)
3. groupby
When you reach for it. "Per", "for each", "how many", "total", "average". You want one number for each city, each customer, each day.
The idea. Split, apply, combine. groupby splits the rows into groups that share a value, you pick a column and what to work out (sum, mean, count, max), and pandas puts one row per group back together. The group key becomes the index of the result.
The code. The table from the reel.
import pandas as pd
df = pd.DataFrame({
"city": ["Rome", "Oslo", "Rome", "Lima", "Oslo", "Rome"],
"qty": [3, 5, 2, 4, 1, 6],
})
out = df.groupby("city")["qty"].sum()
print(out)
city
Lima 4
Oslo 6
Rome 11
Name: qty, dtype: int64
Six rows in, three out, one per city, sorted by city. The result is a Series with the cities as its index. If you want an ordinary table with city as a column, say so:
print(df.groupby("city", as_index=False)["qty"].sum())
city qty
0 Lima 4
1 Oslo 6
2 Rome 11
Several numbers per group at once, each with a name you choose:
summary = df.groupby("city").agg(
total=("qty", "sum"),
orders=("qty", "size"),
biggest=("qty", "max"),
)
print(summary)
total orders biggest
city
Lima 4 1 4
Oslo 6 2 5
Rome 11 3 6
Filtering the groups afterwards is SQL's HAVING:
totals = df.groupby("city")["qty"].sum()
print(totals[totals > 5])
city
Oslo 6
Rome 11
Name: qty, dtype: int64
And when you want the group's number on every original row, for example each row's share of its city's total, use transform. It hands back one value per row instead of one per group:
df["city_total"] = df.groupby("city")["qty"].transform("sum")
df["share"] = (df["qty"] / df["city_total"]).round(2)
print(df)
city qty city_total share
0 Rome 3 11 0.27
1 Oslo 5 6 0.83
2 Rome 2 11 0.18
3 Lima 4 4 1.00
4 Oslo 1 6 0.17
5 Rome 6 11 0.55
What bites. count and size aren't the same thing. size counts rows. count counts values that aren't missing:
import pandas as pd
sales = pd.DataFrame({
"city": ["Oslo", "Oslo", "Rome"],
"qty": [5, None, 2],
})
print(sales.groupby("city")["qty"].count())
print(sales.groupby("city").size())
city
Oslo 1
Rome 1
Name: qty, dtype: int64
city
Oslo 2
Rome 1
dtype: int64
Oslo has two rows but only one qty. "How many orders" usually wants size. The other one is forgetting that the group key moved into the index. If the next step expects a city column, it isn't there until you reset_index() or use as_index=False.
Practise. Use the six-row table from the start of this section.
- The average qty per city. (
df.groupby("city")["qty"].mean(): Lima 4.0, Oslo 3.0, Rome about 3.67.) - The city with the biggest total. (
df.groupby("city")["qty"].sum().idxmax(), which is Rome.) - The number of orders per city, as a table with a column called orders. (
df.groupby("city").size().reset_index(name="orders"))
4. merge
When you reach for it. The data you need is in two tables. Orders and the users who placed them, sales and the products they were for.
The idea. merge is SQL's JOIN. It lines up rows from two DataFrames wherever the key columns match. how picks the join: "inner" (the default) keeps only rows that match on both sides, "left" keeps every row of the left table and fills NaN where nothing matched, "outer" keeps everything from both.
The code. The tables from the reel.
import pandas as pd
orders = pd.DataFrame({
"user_id": [1, 4, 1, 3],
"item": ["book", "cap", "mug", "pen"],
})
users = pd.DataFrame({
"user_id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
})
inner = orders.merge(users, on="user_id")
print(inner)
user_id item name
0 1 book Ana
1 1 mug Ana
2 3 pen Cy
The cap belongs to user 4, who isn't in users, so it's dropped. Ben has no orders, so he's not there either.
left = orders.merge(users, on="user_id", how="left")
print(left)
user_id item name
0 1 book Ana
1 4 cap NaN
2 1 mug Ana
3 3 pen Cy
Every order stays, and the cap gets NaN for a name.
Second shape: who has nothing. Users with no orders. Left join from users, ask pandas to say where each row came from with indicator=True, and keep the rows only the left side had:
both = users.merge(orders, on="user_id", how="left", indicator=True)
print(both)
print(both.loc[both["_merge"] == "left_only", "name"])
user_id name item _merge
0 1 Ana book both
1 1 Ana mug both
2 2 Ben NaN left_only
3 3 Cy pen both
2 Ben
Name: name, dtype: str
When the key has a different name in each table, use left_on and right_on:
people = users.rename(columns={"user_id": "id"})
print(orders.merge(people, left_on="user_id", right_on="id"))
user_id item id name
0 1 book 1 Ana
1 1 mug 1 Ana
2 3 pen 3 Cy
What bites. A key that repeats on the side you expected to be unique. Each match makes a row, so a duplicate user quietly doubles their orders:
dupes = pd.concat([users, users.iloc[[0]]])
print(orders.merge(dupes, on="user_id"))
user_id item name
0 1 book Ana
1 1 book Ana
2 1 mug Ana
3 1 mug Ana
4 3 pen Cy
Five rows from three matching orders. If you know one side should be unique, say so, and pandas checks it for you. The error goes on to list the duplicate keys:
orders.merge(dupes, on="user_id", validate="many_to_one")
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
The other one is whole numbers turning into floats. NaN is a float, so a left join that leaves gaps in a column of ints changes the whole column:
ages = pd.DataFrame({"user_id": [1, 3], "age": [31, 42]})
print(users.merge(ages, on="user_id", how="left"))
user_id name age
0 1 Ana 31.0
1 2 Ben NaN
2 3 Cy 42.0
Practise.
- The orders whose user isn't in users. (
left[left["name"].isna()], which is the cap.) - How many orders each user has, Ben's 0 included. (
users.merge(orders, on="user_id", how="left").groupby("name")["item"].count(): Ana 2, Ben 0, Cy 1. Herecountis the right one, because Ben's row has no item.) - How many rows does
how="outer"give for orders and users, and why? (5: the three matching orders, the cap with no user, and Ben with no order.)
5. pivot tables
When you reach for it. You have long data, one row per thing that happened, and you want a grid: cities down the side, quarters across the top, totals in the cells. Reports, charts, and comparing groups side by side.
The idea. pivot_table takes three columns. index becomes the rows of the grid, columns becomes its columns, and values fills the cells. When more than one row lands in the same cell, aggfunc decides how they're combined.
The code. The table from the reel.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Oslo", "Rome", "Rome", "Oslo"],
"qtr": ["Q1", "Q2", "Q1", "Q2", "Q1"],
"sales": [3, 5, 4, 2, 6],
})
wide = df.pivot_table(
index="city",
columns="qtr",
values="sales",
aggfunc="sum",
)
print(wide)
qtr Q1 Q2
city
Oslo 9 5
Rome 4 2
Five rows in, a 2 by 2 grid out. Oslo had two Q1 rows, 3 and 6, and the cell holds their sum.
A combination with no rows comes out as NaN. fill_value puts something else there, and margins=True adds totals:
more = pd.concat([df, pd.DataFrame({"city": ["Lima"], "qtr": ["Q2"], "sales": [7]})])
print(more.pivot_table(index="city", columns="qtr", values="sales", aggfunc="sum"))
print(more.pivot_table(index="city", columns="qtr", values="sales", aggfunc="sum",
fill_value=0, margins=True))
qtr Q1 Q2
city
Lima NaN 7.0
Oslo 9.0 5.0
Rome 4.0 2.0
qtr Q1 Q2 All
city
Lima 0 7 7
Oslo 9 5 14
Rome 4 2 6
All 13 14 27
The same grid can come from a groupby on two columns, with the second key moved across the top by unstack:
print(df.groupby(["city", "qtr"])["sales"].sum().unstack())
qtr Q1 Q2
city
Oslo 9 5
Rome 4 2
And melt turns the grid back into long rows:
print(wide.reset_index().melt(id_vars="city", value_name="sales"))
city qtr sales
0 Oslo Q1 9
1 Rome Q1 4
2 Oslo Q2 5
3 Rome Q2 2
What bites. Leaving out aggfunc. The default is the mean, not the sum, so Oslo's Q1 comes out as 4.5:
print(df.pivot_table(index="city", columns="qtr", values="sales"))
qtr Q1 Q2
city
Oslo 4.5 5.0
Rome 4.0 2.0
The other one is pivot, without _table. It only reshapes and never combines, so two rows for the same cell stop it:
df.pivot(index="city", columns="qtr", values="sales")
ValueError: Index contains duplicate entries, cannot reshape
Use pivot when every combination appears once, and pivot_table when it might not.
Practise.
- How many rows went into each cell? (
df.pivot_table(index="city", columns="qtr", values="sales", aggfunc="size"): 2 for Oslo Q1, 1 for the rest.) - The biggest single sale in each cell. (
aggfunc="max": Oslo Q1 is 6.) - Quarters down the side and cities across the top. (Swap them:
index="qtr", columns="city".)
how to practise with this
One section at a time. Type the section's table in yourself, run each block, and check you get the same output before you change anything. Then do its practise questions without looking at the answers in brackets.
Before you write anything, say what one row of the answer is: one per city, one per order, one per user. That sentence tells you whether you need a filter, a groupby or a merge, the same way it does in SQL.
honest limitations
Five things isn't all of pandas. Reading files (read_csv), missing values (fillna, dropna), dates, and apply all come up early, and they aren't covered here. concat only turns up in passing.
The tables are tiny on purpose, so you can check every number by eye. On big data the same code works, but how you write it starts to matter for speed. A rule that holds up: if you're writing a Python loop over the rows of a DataFrame, there's usually a column-at-a-time way to do it.
Everything was run on pandas 3.1.1 and checked again on 2.3.3. Versions older than that may word some messages differently. pandas 3 always treats a slice of a DataFrame as a copy when you set values on it, which is where the warning in section 1 comes from. If the plain Python around your pandas is what slows you down, the python cheat sheet covers the syntax that comes up most.