Sub topic 2
Going back and forth: `melt` and `pivot` as inverses
Assume you know basic pandas DataFrames and can use groupby with aggregation functions such as sum and mean. This chapter focuses on choosing a reshape operation and handling duplicate keys.
Round-tripping between layouts
A wide table stores related measurements in separate columns. A long table stores the measurement name in one column and its value in another. melt converts wide data to long data. pivot reverses that transformation when each index-and-column pair identifies one value.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(
id_vars="store",
var_name="month",
value_name="sales",
)
back = long.pivot(
index="store",
columns="month",
values="sales",
).reset_index()
back.columns.name = None
print(long)
print(back)The round trip works because each store and month pair occurs exactly once.
When `pivot` fails
pivot cannot decide what to place in a cell when an index-and-column pair appears more than once.
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
try:
sales.pivot(index="store", columns="month", values="sales")
except ValueError as err:
print("pivot failed:", err)Here, store A has two January values. The duplicate key is ("A", "jan"). Decide how to combine those values before reshaping.
Aggregate with `pivot_table`
pivot_table accepts an aggregation function, or aggfunc. It combines duplicate values while creating the wide table.
table = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="total",
)
print(table)This sums duplicate January rows, replaces missing cells with 0, and adds total rows and columns.
Exercise
Which operation should you use when two rows share the same index and column keys?
Show answer
Use pivot_table with an appropriate aggfunc, such as sum or mean.