Ravindra BagaleCourses & study guides मराठी Track your progress

11. Reshape and Wide/Long Data

Data Science

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

Use pivot only when each city and month pair appears once. In this sample Pune has two October rows (900 and 400), so pivot stops with the error "Index contains duplicate entries", while pivot_table combines them. Remember that pivot_table takes the mean by default, so write aggfunc="sum" when you want totals; that is why Pune shows 1300 for October here.