Sub topic 2
Sorting and Summarising Data in pandas
This chapter assumes you can create a pandas DataFrame, select columns, and distinguish a Series from a DataFrame.
Stable sorts and `ignore_index`
A stable sort preserves the original order of rows whose sort values are equal. Use kind="stable" when that order carries meaning. ignore_index=True replaces the old row labels with 0, 1, 2, ....
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Bo", "Cy", "Dee"],
"score": [80, 80, 70, 90],
})
result = df.sort_values(
"score",
ascending=False,
kind="stable",
ignore_index=True,
)
print(result)The two rows scoring 80 remain in their original order: Ana, then Bo.
Finding the top and bottom rows
Use nlargest and nsmallest when you need rows rather than a complete sort.
print(df.nlargest(2, "score"))
print(df.nsmallest(2, "score"))Missing numeric values are generally excluded from these selections unless there are not enough non-missing rows.
Ranking values
rank assigns positions. By default, tied values receive their average rank. method="dense" gives tied values the same rank without gaps.
df["rank"] = df["score"].rank(method="dense", ascending=False)
print(df)A missing score receives a missing rank.
Summarising columns with `describe` and reductions
describe() gives common statistics such as count, mean, standard deviation, minimum, and quartiles. Reductions such as sum(), mean(), and median() produce one summary value.
print(df["score"].describe())
print(df["score"].mean())
print(df["score"].sum())These operations skip missing values by default. count() counts non-missing values, while size counts rows.
Counting categories with `value_counts`
value_counts() counts each distinct value from most common to least common. Use normalize=True for proportions. Missing values are omitted unless you pass dropna=False.
print(df["score"].value_counts())
print(df["score"].value_counts(normalize=True))Aggregating by group with `groupby`
groupby divides rows into groups, then applies a reduction to each group.
sales = pd.DataFrame({
"region": ["North", "North", "South"],
"units": [10, 8, 5],
})
summary = sales.groupby("region")["units"].agg(["sum", "mean", "count"])
print(summary)By default, rows with a missing group label are excluded. Use groupby("region", dropna=False) to retain that group.
Exercise
Which option preserves the order of tied rows and creates a fresh index?
Show answer
Use sortvalues(..., kind="stable", ignoreindex=True).