Reshape a long event table into a wide cohort matrix — pivot or melt?
df is long: cohort_month, activity_month, users, one row per cell. Reshape it into a wide matrix indexed by cohort_month with one column per activity_month holding users.
import pandas as pd
def cohort_matrix(df: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
pivot goes long to wide: df.pivot(index='cohort_month', columns='activity_month', values='users'). melt is the inverse, wide to long. Use pivot only when the index/column pair is unique; if a cell can repeat, pivot_table(..., aggfunc='sum') aggregates the collisions instead of raising.
- ✗Swapping pivot and melt — reaching for melt to widen the frame
- ✗Calling pivot when index/column pairs repeat and hitting a ValueError
- ✗Assuming pivot aggregates duplicates like pivot_table does
- →When must you switch from pivot to pivot_table?
- →How does melt name its value and variable columns?
pivot spreads the long rows into a matrix: cohort_month becomes the index, activity_month becomes the columns, users fills the cells.
import pandas as pd
def cohort_matrix(df: pd.DataFrame) -> pd.DataFrame:
return df.pivot(index='cohort_month',
columns='activity_month',
values='users')
melt is the round-trip back to long form. pivot errors on a duplicated index/column pair — switch to pivot_table(index=..., columns=..., values='users', aggfunc='sum') when a cell can legitimately hold several rows.