Sub topic 11
Summarize first, then plot: groupby, pivot_table and value_counts
This chapter assumes you can build a DataFrame, select columns, and call groupby in pandas. It also assumes matplotlib is installed. Raw rows rarely make a good chart. A table of 10,000 orders gives 10,000 points, but a chart of revenue per region needs one number per region. So you summarize first, then plot the result.
Why the summary's index matters
df.plot draws the index on the x axis and one series per column. The summarizing functions groupby, pivot_table and value_counts all put the group labels in the index. That makes their output ready to plot with no set_index step.
One number per category with groupby
Select one column, aggregate it, and the result is a Series. Its index holds the categories.
import pandas as pd
import matplotlib.pyplot as plt
orders = pd.DataFrame({
"region": ["north", "south", "north", "east", "south", "north"],
"product": ["pen", "pen", "ink", "ink", "ink", "pen"],
"amount": [10, 20, 15, 5, 30, 25],
})
totals = orders.groupby("region")["amount"].sum().sort_values()
totals.plot.barh(title="Revenue by region")
plt.show()Calling sort_values() before plotting orders the bars. Without it, the bars follow the alphabetical group order. For a horizontal bar chart, ascending order puts the largest bar at the top.
Counting categories with value_counts
value_counts counts how often each value occurs. It sorts from most to least frequent, so the result is often chart-ready.
orders["region"].value_counts().plot.bar(rot=0, title="Orders per region")
plt.show()Use value_counts(normalize=True) to plot shares instead of counts. This works well with plot.pie.
Two categories with pivot_table
To compare regions across products, you need one column per product. pivot_table builds that layout: one categorical field becomes the index, and another becomes the columns.
table = orders.pivot_table(
index="region",
columns="product",
values="amount",
aggfunc="sum",
fill_value=0,
)
print(table)
table.plot.bar(rot=0, title="Revenue by region and product")
table.plot.bar(stacked=True, rot=0, title="Stacked")
plt.show()The first call draws grouped bars, one group per region and one bar per product. The second stacks the products inside each region. The fill_value=0 argument replaces combinations with no orders. Without it they become NaN, which plots as a gap.
You can get the same shape from groupby with two keys followed by unstack():
orders.groupby(["region", "product"])["amount"].sum().unstack(fill_value=0).plot.bar(rot=0)
plt.show()Common mistakes
- Plotting the whole
groupbyresult.orders.groupby("region").sum()aggregates every column. Text columns such asproductget concatenated into long strings, and they are dropped or raise errors in newer pandas versions. Select the column you want first, as in["amount"]. - Categories on the wrong axis. If the groups appear as separate lines or bars when you wanted them along the x axis, the table is the wrong way round. Call
.Tto transpose it. - Losing the labels with
as_index=False. This option moves the group keys into a column, so the x axis shows 0, 1, 2. Keep the default, or callset_indexafterward.
Exercises
Exercise
You have a DataFrame sales with columns city, channel and revenue. Write one expression that draws a stacked bar chart with one bar per city, split by channel, using total revenue.
Show answer
sales.pivot_table(index="city", columns="channel", values="revenue", aggfunc="sum", fill_value=0).plot.bar(stacked=True). The equivalent is sales.groupby(["city", "channel"])["revenue"].sum().unstack(fill_value=0).plot.bar(stacked=True).
Exercise
A chart made from df.groupby("region", as_index=False)["amount"].sum() shows 0, 1, 2 on the x axis instead of region names. Why, and how do you fix it?
Show answer
With as_index=False the region names stay in a column and the index becomes the default integers, which plot uses for the x axis. Remove as_index=False, or call .set_index("region") before plotting.