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.
More Related questions...