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
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.
Ravindra Bagale's Tip – मराठी
प्रत्येक city आणि month ची जोडी एकदाच येत असेल तेव्हाच pivot वापरा. या sample मध्ये Pune च्या October च्या दोन rows आहेत (900 आणि 400), म्हणून pivot "Index contains duplicate entries" असा error देऊन थांबतो, तर pivot_table त्या दोन्ही rows एकत्र करतो. लक्षात ठेवा, pivot_table default ने mean काढतो, म्हणून total हवा असेल तर aggfunc="sum" लिहा; म्हणूनच इथे Pune च्या October समोर 1300 दिसतो.
Ravindra Bagale's Tip – हिंदी
pivot तभी इस्तेमाल करो जब हर city और month की जोड़ी सिर्फ़ एक बार आए। इस sample में Pune की October वाली दो rows हैं (900 और 400), इसलिए pivot "Index contains duplicate entries" error देकर रुक जाता है, जबकि pivot_table उन दोनों rows को जोड़ देता है। याद रखो, pivot_table default में mean निकालता है, इसलिए total चाहिए तो aggfunc="sum" लिखो; इसी वजह से यहाँ Pune के October में 1300 दिखता है।