Pandasdrill

pandas interview questions, with answers you can run

These are the question types that come up in the pandas part of a data analyst interview: a small table, a business question, and no hint about which method to use. Each one has a short answer, code that runs as shown, and the mistake that usually costs the point.

Filtering and selecting

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.

How do you filter rows on two conditions?

Build one boolean mask per condition, wrap each in parentheses and join them with & (and) or | (or). The parentheses are required because & binds tighter than the comparisons.

orders[(orders["status"] == "completed") & (orders["amount"] >= 150)]

Result:

   order_id customer       date  amount     status
1         2    birch 2024-01-12   300.0  completed
4         5     dune 2024-02-10   210.0  completed
5         6    birch 2024-02-20   150.0  completed
7         8   cobalt 2024-03-15   500.0  completed

Write it yourself: Excel SUMIFS: a total with two conditions, checked on two datasets.

What is the difference between loc and iloc?

loc selects by label (index values and column names) and includes the end of a slice. iloc selects by position and excludes the end, like normal Python slicing.

orders.loc[0:2, ["customer", "amount"]]

Result:

  customer  amount
0     acme   120.0
1    birch   300.0
2     acme    80.0

Write it yourself: Rows and columns with loc, checked on two datasets.

Try it yourself

The sales lead asks: which countries bring in the most money? Count completed orders only. Return a DataFrame with the columns country and revenue, highest revenue first.

orders: 12 rows, first 4 shown

order_idcustomerdateamountstatus
1"acme"2024-01-05120"completed"
2"birch"2024-01-12300"completed"
3"acme"2024-01-2880"completed"
4"cobalt"2024-02-0345"cancelled"

customers: 6 rows, first 4 shown

customercountrysegment
"acme""US""retail"
"birch""UK""wholesale"
"cobalt""US""retail"
"dune""DE""retail"

Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.

Grouping and aggregating

Total revenue per customer, completed orders only, largest first.

Filter first, then group, then sort. Forgetting the filter is the classic mistake: cancelled orders sit in the same table with a real amount, and nothing fails if you include them.

done = orders[orders["status"] == "completed"]
done.groupby("customer", as_index=False)["amount"].sum().sort_values("amount", ascending=False)

Result:

  customer  amount
2   cobalt   500.0
1    birch   450.0
0     acme   260.0
3     dune   210.0

Write it yourself: Revenue by country, checked on two datasets.

What is each customer's share of total revenue?

Compute the share against the full total before you cut the table down. Taking the top three first and then dividing makes their shares add up to 100%, which is wrong.

done = orders[orders["status"] == "completed"]
rev = done.groupby("customer")["amount"].sum()
(rev / rev.sum()).round(3).sort_values(ascending=False)

Result:

customer
cobalt    0.352
birch     0.317
acme      0.183
dune      0.148

Write it yourself: Top three customers and their share, checked on two datasets.

What is the difference between agg and transform?

agg returns one row per group. transform returns one value per original row, so the result can be assigned straight back as a new column, for example each order's share of its customer's total.

orders.assign(cust_total=orders.groupby("customer")["amount"].transform("sum"))[["customer", "amount", "cust_total"]].head(4)

Result:

  customer  amount  cust_total
0     acme   120.0       260.0
1    birch   300.0       450.0
2     acme    80.0       260.0
3   cobalt    45.0       545.0

Write it yourself: Share of the group total with transform, checked on two datasets.

Find each customer's most recent order.

Sort by date and keep the last row of each group. Do not take max of the date and max of the amount separately: the two maximums can come from different orders.

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

Write it yourself: SQL ROW_NUMBER: latest order per customer, checked on two datasets.

Merging

What is the difference between an inner and a left merge?

An inner merge keeps only rows with a match on both sides. A left merge keeps every row of the left table and fills the right-hand columns with NaN where there is no match. merge defaults to inner, which silently drops unmatched rows.

customers.merge(orders.groupby("customer", as_index=False)["amount"].sum(), on="customer", how="left")

Result:

  customer country    segment  amount
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     NaN

Write it yourself: Left merge keeps every order, checked on two datasets.

Which customers have never placed an order?

This is an anti-join. isin marks the customers that appear in orders and ~ flips the mask.

customers[~customers["customer"].isin(orders["customer"])]

Result:

  customer country    segment
4    ember      UK  wholesale

Write it yourself: Customers who never ordered, checked on two datasets.

Your total doubled after a merge. Why?

A merge returns one row for every matching pair. If the key is repeated in the lookup table, each matching row on the left is duplicated. Compare the row counts before and after, and remove the repeated keys first.

print(len(lines), "rows before,", len(lines.merge(dup_prices, on="sku", how="left")), "rows after a left merge on a table with a repeated key")
lines.merge(dup_prices.drop_duplicates(), on="sku", how="left")

Result:

4 rows before, 5 rows after a left merge on a table with a repeated key
   order_id sku  qty  price
0         1   A    2   10.0
1         2   B    1   25.0
2         3   D    4    NaN
3         4   A    3   10.0

Write it yourself: A join that inflates the total, checked on two datasets.

Dates and cleaning

Revenue per month and month-over-month growth.

Turn each date into its month, total per month, then use pct_change. The first month stays missing because there is nothing to compare it with.

done = orders[orders["status"] == "completed"]
m = done.groupby(done["date"].dt.strftime("%Y-%m"))["amount"].sum().rename_axis("month").reset_index(name="revenue")
m.assign(growth=m["revenue"].pct_change().round(3))

Result:

     month  revenue  growth
0  2024-01    500.0     NaN
1  2024-02    360.0  -0.280
2  2024-03    560.0   0.556

Write it yourself: Month over month revenue growth, checked on two datasets.

Amounts arrive as text like $1,200.50. How do you total them?

Strip the symbols with a string replace and convert to float before any arithmetic. Clean the group labels too, or East and east become two groups.

clean = raw.assign(region=raw["region"].str.strip().str.lower(), amount=raw["amount"].str.replace("[$,]", "", regex=True).astype(float))
clean.groupby("region", as_index=False)["amount"].sum()

Result:

  region  amount
0   east  1500.5
1   west    45.0

Write it yourself: Messy export: clean, then total, checked on two datasets.

Count how many orders of each status every customer has.

crosstab counts the combinations of two columns and fills the gaps with 0. It is the pandas form of several conditional counts side by side.

pd.crosstab(orders["customer"], orders["status"])

Result:

status    cancelled  completed
customer                      
acme              0          3
birch             0          2
cobalt            1          1
dune              0          1

Write it yourself: SQL CASE WHEN inside a count, 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.

Start practicing free

Related guides