Python / Data Science Essentials Interview Questions
How do you use pd.pivot_table to summarise data?
pd.pivot_table reshapes and aggregates a DataFrame simultaneously, producing a cross-tabulation — exactly like a spreadsheet pivot table. It is the go-to function for producing summary reports broken down by two categorical dimensions.
import pandas as pd
sales = pd.DataFrame({
'region': ['East','East','West','West','East','West','West'],
'quarter': ['Q1', 'Q2', 'Q1', 'Q2', 'Q1', 'Q1', 'Q2'],
'product': ['A', 'A', 'A', 'A', 'B', 'B', 'B'],
'revenue': [100, 120, 90, 110, 80, 70, 95],
})
# Basic pivot: average revenue by region (rows) and quarter (columns)
pt = pd.pivot_table(
sales,
values='revenue',
index='region',
columns='quarter',
aggfunc='sum', # sum, mean, count, np.median, list, ...
fill_value=0, # replace NaN with 0
margins=True, # add row/column totals (labelled 'All')
margins_name='Total',
)
print(pt)
# quarter Q1 Q2 Total
# region
# East 180 120 300
# West 160 205 365
# Total 340 325 665
# Multiple values and multiple aggregations
pd.pivot_table(sales, values='revenue', index='region',
columns='product', aggfunc=['sum', 'count'])The inverse operation — converting a wide pivot back to long form — is pd.melt(). df.stack() and df.unstack() do similar reshape operations on the index levels directly.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
