Sub topic 4
Chainable methods you will use most
This chapter assumes you can build a DataFrame, select columns, filter rows with boolean masks, and run a basic groupby. It also assumes you know that most DataFrame methods return a new DataFrame, which the earlier chapters covered. Here you will meet the five methods that appear in most real chains, with the behavior and edge cases that trip people up.
What makes a method chainable
A method is chainable when it returns a DataFrame (or a GroupBy object that you can finish with another method). The next call in the chain then runs on that return value. A method that modifies the DataFrame in place and returns None breaks the chain, because the next .method() would be called on None.
The five methods below all return new objects, so they fit anywhere in a chain.
| Method | Purpose | Main thing to watch |
|---|---|---|
| `rename` | Change column or index labels | Use `columns=`, and don't pass `inplace=True` |
| `query` | Filter rows with a string expression | Quoting, `@` variables, backticks for odd names |
| `sort_values` | Order rows by one or more columns | Keeps the old index labels; ties may reorder |
| `reset_index` | Replace the index with 0, 1, 2, ... | `drop=True` unless you want the old index as a column |
| `groupby` + `agg` | Summarize groups of rows | Named aggregation; `as_index=False` |
The examples use the same small DataFrame as the rest of the tutorial.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})rename: change labels without touching the data
rename takes a dictionary that maps old labels to new ones. Pass it as columns= so the intent is clear. Labels you don't mention stay as they are.
renamed = df.rename(columns={"price": "unit_price", "quantity": "qty"})
print(renamed.columns.tolist())
print(df.columns.tolist())The first line prints ['order_id', 'region', 'unit_price', 'qty']. The second prints the original names, because rename returned a new DataFrame and left df alone.
Two details matter in practice:
- A key that does not exist is silently ignored by default. A typo such as
"prise"produces no error. Passerrors="raise"if you want aKeyErrorinstead. renamealso accepts a function, for exampledf.rename(columns=str.upper). This is handy for cleaning many names at once, such asstr.striporstr.lower.
query: filter rows with a readable string
query evaluates a string expression against the columns and keeps the rows where it is true. In a chain it usually reads better than df[df["revenue"] > 20], because it does not need to name the intermediate DataFrame.
threshold = 20
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > @threshold and region == 'west'")
)
print(result)Only order 4 survives (revenue 50, region west). Order 2 has revenue 20, which is not greater than 20.
Points to remember:
- Column names are used bare. String values need quotes inside the expression, so you alternate quote styles:
"region == 'west'". - Prefix a Python variable with
@to read it from the surrounding scope, as@thresholddoes above. - Use
and,or, andnot(or&,|,~). You do not need the parentheses that boolean masks require. - A column name that is not a valid Python identifier must be wrapped in backticks.
spaced = df.rename(columns={"price": "unit price"})
print(spaced.query("`unit price` > 12"))This keeps orders 2 and 3, the rows with a price above 12.
A useful property of query for chains is that it sees the DataFrame produced by the previous step, including columns that assign just created. A mask written against df cannot do that, because df does not have the new column.
sort_values: order rows, keep their labels
sort_values takes a column name or a list of names. For several keys, ascending can be a list with one entry per key.
ordered = df.sort_values(["region", "price"], ascending=[True, False])
print(ordered)Rows are grouped alphabetically by region, and within each region the highest price comes first. The row labels move with their rows. The printed index will look like 0, 2, 1, 3, not 0, 1, 2, 3.
Three edge cases are worth knowing:
- Missing values go last by default. Use
na_position="first"to change that. - The default sorting algorithm is not guaranteed to keep tied rows in their original order. If ties matter, pass
kind="stable". sort_values(..., ignore_index=True)renumbers the result in one step. This is a shortcut for adding.reset_index(drop=True).
reset_index: renumber after the index goes stale
Filtering and sorting leave the old labels in place. That is correct behavior, but a scrambled index is rarely useful in a final result. reset_index replaces it with a fresh 0, 1, 2, ... index.
ranked = (
df
.sort_values("quantity", ascending=False)
.reset_index(drop=True)
)
print(ranked)The drop=True argument matters. Without it, pandas keeps the old index and inserts it as a new column named index, which is almost never what you want in the middle of a chain. Use reset_index() without drop only when the index holds real information, such as group labels you need as a column.
groupby and agg: summarize inside the chain
A groupby call returns a GroupBy object, not a DataFrame. Calling agg on it returns a DataFrame again, so the chain continues. Named aggregation is the clearest form. Each keyword becomes an output column, and its value is a (column, function) pair.
summary = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
.sort_values("total_revenue", ascending=False)
)
print(summary)The printed result looks like this:
region total_revenue orders
1 west 70.0 2
0 east 65.0 2West has revenue of 20 + 50 and east has 20 + 45, so west sorts first.
The as_index=False argument keeps region as an ordinary column. Without it, region becomes the index, and a later .sort_values("region") or .query("region == 'east'") still works for query but will confuse readers of the code. The alternative is to add .reset_index() after agg. Both give the same table, but as_index=False says the intent at the point where the grouping is defined.
Look at the index in the output above: 1, 0. The sort moved the rows but kept their labels. Add .reset_index(drop=True) at the end if the result will be displayed or saved.
Putting the methods in order
The order of steps changes both speed and correctness. A good default is to reduce the data early and clean it up late.
- Rename and compute columns first, so the later steps use clear names.
- Filter before you aggregate or sort, so those steps handle fewer rows.
- Aggregate.
- Sort the summary.
- Reset the index last, because every earlier step can disturb it.
Here is one chain that uses all five methods. It follows the order above.
report = (
df
.rename(columns={"price": "unit_price", "quantity": "qty"})
.assign(revenue=lambda d: d["unit_price"] * d["qty"])
.query("revenue > 10")
.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
.sort_values("total_revenue", ascending=False)
.reset_index(drop=True)
)
print(report)After the filter, orders 1, 2, 3, and 4 all remain (revenues 20, 20, 45, 50). The report lists west with 70.0 and east with 65.0, each with 2 orders, numbered 0 and 1.
Common mistakes
The first mistake is using inplace=True inside a chain. Methods such as rename and sort_values accept it, but they then return None.
# Raises AttributeError: 'NoneType' object has no attribute 'query'
# df.rename(columns={"price": "unit_price"}, inplace=True).query("unit_price > 5")Leave inplace out and assign the final chain to a name.
The second mistake is calling a method and discarding the result. The line df.sort_values("price") on its own computes a sorted copy and throws it away. df is unchanged.
The third mistake is a query string that refers to a column the chain no longer has. If groupby(...).agg(...) renamed or dropped a column, a later query on the old name raises an UndefinedVariableError. Read each step as working on the output of the step above it.
Exercises
Exercise
Starting from df, write one chain that keeps orders with a price of at least 10, totals quantity for each region as a column named total_quantity, sorts so the largest total comes first, and renumbers the index from 0. What does the result contain?
Show answer
One chain is df.query("price >= 10").groupby("region", asindex=False).agg(totalquantity=("quantity", "sum")).sortvalues("totalquantity", ascending=False).reset_index(drop=True), wrapped in parentheses so it can span several lines. Orders 1, 2, and 3 pass the filter. East has quantity 2 + 3 = 5 and west has 1, so the result has two rows: east with 5 at index 0, then west with 1 at index 1.
Exercise
A colleague writes df.sortvalues("price", inplace=True).resetindex(drop=True) and gets an AttributeError. Why does it fail, and how do you fix it?
Show answer
With inplace=True, sortvalues modifies df and returns None, so resetindex is called on None. Remove inplace=True and assign the result: df = df.sortvalues("price").resetindex(drop=True), or put both calls in a chain assigned to a new name.
Exercise
After sortvalues("totalrevenue", ascending=False), the index of a summary reads 1, 0. Name two ways to get 0, 1 without a separate statement.
Show answer
Add .resetindex(drop=True) as the last step of the chain, or pass ignoreindex=True to sort_values.