Sub topic 4
Chainable methods you will use most
This chapter assumes you can filter rows, select columns, and run a basic groupby in pandas. Here you will meet the five methods that make up most chains: rename, query, sort_values, reset_index, and groupby with agg. Each takes a DataFrame and returns a new object, so you can attach the next call directly.
The examples use this DataFrame:
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],
})The core methods
| Method | What it does | Returns |
|---|---|---|
| `rename` | Changes column or index labels | DataFrame |
| `query` | Keeps rows that match a condition written as a string | DataFrame |
| `sort_values` | Orders rows by one or more columns | DataFrame |
| `reset_index` | Replaces the index with `0, 1, 2, ...` | DataFrame |
| `groupby` | Splits rows into groups | GroupBy object |
| `agg` | Summarizes each group | DataFrame |
groupby is the exception. It returns a GroupBy object, which holds the groups but is not yet a table. You must call an aggregation such as agg to get a DataFrame back.
A first chain
This chain renames a column, filters, sorts, and cleans up the index:
result = (
df
.rename(columns={"order_id": "id"})
.query("price >= 10")
.sort_values("price", ascending=False)
.reset_index(drop=True)
)
print(result) id region price quantity
0 2 west 20.0 1
1 3 east 15.0 3
2 1 east 10.0 2The original df is unchanged. Each step receives the result of the step above it.
Details that matter in each method
rename takes a dictionary of old and new names. Labels that are not in the dictionary stay as they are. It also accepts a function, so .rename(columns=str.upper) changes every column name.
query takes a string. Column names are written without quotes or df[...]. To use a Python variable, prefix it with @:
min_price = 12
expensive = df.query("price > @min_price")query only works with column names that are valid identifiers. For names with spaces, use a different filter, or wrap the name in backticks, as in ` unit price > 3 `.
sort_values takes a column name or a list of names. Pass ascending=False for descending order, or a list of booleans to mix directions.
reset_index matters because query and sort_values keep the original row labels. After sorting, your index might read 2, 0, 1. Use reset_index(drop=True) to renumber the rows and discard the old labels. Without drop=True, pandas adds the old index back as a new column, which is rarely what you want at the end of a chain.
Summarizing with groupby and agg
Named aggregation, written as new_name=("column", "function"), gives readable output columns:
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)
.reset_index(drop=True)
)
print(summary) region total_revenue orders
0 west 70.0 2
1 east 65.0 2Passing as_index=False keeps region as a normal column. Without it, region becomes the index, and you would need another reset_index() before further steps could treat it as a column. The assign call is covered in the next chapter. For now, read it as "add a revenue column."
Common mistakes
- Leaving off
drop=Trueinreset_index, which adds an unwantedindexcolumn. - Chaining after
groupbywithout an aggregation. A GroupBy object lacks DataFrame methods such asquery. - Writing
query("region == east")without quotes around the string value. Usequery("region == 'east'").
Exercise
Starting from the df above, write a chain that keeps only rows where quantity is greater than 1, renames "price" to "unitprice", sorts by "unitprice" from highest to lowest, and renumbers the rows from 0.
Show answer
result = ( df .query("quantity > 1") .rename(columns={"price": "unitprice"}) .sortvalues("unitprice", ascending=False) .resetindex(drop=True) ) The query keeps orders 1, 3, and 4. After sorting, the unit prices read 15.0, 10.0, 5.0, and the index is 0, 1, 2. You can also rename first, as long as the query and sort use the matching column name.