Ravindra BagaleCourses & study guides

11. Reshape and Wide/Long Data

11.3 pivot_table — Long to Wide / Summary

# From transactional long data
tx = pd.DataFrame({
    "city": ["Pune", "Pune", "Nashik", "Pune", "Nashik", "Nagpur"],
    "month": ["Sep", "Oct", "Oct", "Oct", "Sep", "Oct"],
    "amount": [320, 900, 450, 400, 200, 240],
})
pt = pd.pivot_table(
    tx, index="city", columns="month", values="amount",
    aggfunc="sum", fill_value=0,
)
pt
# Margins = totals
pd.pivot_table(tx, index="city", columns="month", values="amount",
               aggfunc="sum", margins=True, margins_name="Total")

Ravindra Bagale's Tip

Khup students pivot aani pivot_table guntat. pivot wants unique index+column pairs; duplicates → error. Aggregations havi asel tar pivot_table. Lakshat theva!