How to make a pivot table in pandas with pivot_table
A pivot table in pandas is built with pivot_table, which takes the field that goes in the rows (index), the field that goes in the columns (columns), the number being summarized (values), and the calculation to apply (aggfunc). Every field in an Excel pivot table maps directly to one of those four arguments, and the result is an ordinary DataFrame you can chart, export, or feed into a model. The walkthrough below goes from the first lines of code to multiple aggregations, nested indexes, and grand totals.
How do you make a pivot table in pandas, step by step?
The routine is the same every time: load the data, check the column types, choose the row and column fields, pick the number to summarize, and set the aggregation function. Anyone who already builds pivot tables in Excel recognizes the logic — the difference is that here the fields are passed as named arguments.
The default function in pivot_table is the mean, not the sum. If you leave aggfunc out, pandas returns the average for each intersection, which is the most common surprise for people coming from Excel.
- Load the data: import pandas as pd; sales = pd.read_csv('sales.csv')
- Inspect before aggregating: sales.dtypes and sales.head()
- Build the table: sales.pivot_table(index='region', values='amount', aggfunc='sum')
- Assign the result to a variable and keep working from that DataFrame
How do you apply more than one aggregation to the same table?
Pass a list to aggfunc and you get one column per function. The example below returns sum, mean, and count of the same value, with a second column level naming the function that produced each number.
A dictionary works when each numeric column needs a different treatment — useful when the column you want to sum is not the column you want to average.
With more than one function the columns become a MultiIndex. To export or keep analyzing, flatten the labels with table.columns = ['_'.join(map(str, c)) for c in table.columns] and then call reset_index() to turn the indexes into regular columns.
- sales.pivot_table(index='region', values='amount', aggfunc=['sum','mean','count'])
- sales.pivot_table(index='region', aggfunc={'amount':'sum','quantity':'mean'})
- Aggregations you will use most: sum, mean, median, count, min, max, and nunique
- Custom functions go in as a lambda, for example aggfunc=lambda x: x.max() - x.min()
How do you use multiple indexes and crossed columns?
To reproduce the Excel layout with two or three variables in the rows, pass a list to index. The order of the list is the order of the levels in the result: the first item becomes the outermost level.
Crossed columns go in columns. With index=['country','state'] and columns='channel', each cell shows the summary for that combination. The margins=True argument adds the totals row and column, and margins_name sets the label for that total.
When the result carries a MultiIndex, slice one level with xs(), and use reset_index() to get back a flat table that exports cleanly or merges with another DataFrame.
- sales.pivot_table(index=['country','state'], columns='channel', values='amount', aggfunc='sum')
- Add fill_value=0, margins=True and margins_name='Total' to close the table
- Set dropna=False when you want to keep categories with no records
- Keep index lists short: too many row variables make the table hard to read
How do you add totals, handle empty cells, and calculate percentages?
An empty cell in pivot_table comes back as NaN, not as zero. The fill_value=0 argument fixes the presentation, but check first whether the gap means no record exists or a value is missing in the source — the two cases need different treatment.
Percentages are ordinary arithmetic once the table exists: sum the value column, divide each row by that total, and multiply by 100. pd.crosstab does the same cross-tabulation when you only need counts and proportions.
Before exporting to Excel, call round() on the numeric columns and reset_index() so the index levels become columns. The file then opens looking like a finished pivot table.
- table['pct'] = (table['amount'] / table['amount'].sum() * 100).round(1)
- table = table.round(2).reset_index() to leave a clean output
- table.to_excel('summary.xlsx') to share the result
- For counts by category, pd.crosstab(sales['region'], sales['channel']) does the same cross-tab
Should you use pivot_table or groupby?
groupby returns a long, tidy table: one row per combination, with the grouping keys as columns. pivot_table spreads one of those variables across the top, so the shape of the result becomes part of the answer.
Choose groupby when the next step is more computation, joins, or modeling input, because the long shape is easier to chain. Choose pivot_table when the layout itself is the deliverable — a report, a dashboard input, or a file somebody will open in Excel.
One practical difference: pivot drops rows where the index and column combination repeats, while pivot_table aggregates them. If your data has duplicates and you call pivot, expect an error instead of a number.
- groupby(...).agg(...) when you need a long table or several derived columns
- pivot_table when the cross-tab layout is what gets read or exported
- pivot_table with aggfunc='count' to check how many records sit behind each cell
What should you practice after you can build a pivot table?
One messy file exercises every parameter above: category labels that need standardizing, dates stored as text, missing values, and a numeric column that arrives with currency symbols. Cleaning comes before aggregating, and outlier detection comes before you trust a mean.
The Python for Data Science and Analytics course covers that ground in order: IDE and Jupyter Notebook setup, basic functions, NumPy and pandas, user-defined functions, loops and conditionals, data visualization, then data cleaning and preparation including outlier detection. It runs from zero to advanced across three main modules — Basic, Intermediate, and Advanced — plus bonus modules, and closes with a final project that goes from exploratory analysis to end-to-end machine learning. Lessons are recorded in high quality and watched at your own pace, with guided exercises, real market projects for your portfolio, a certificate on completion, an exclusive community for networking, and unlimited access with no expiry date.
The price is R$ 470, or 12 installments of R$ 20,37 on a credit card, paid through the Hotmart checkout, which also accepts boleto. No prior programming experience is required to start. Full details are at python.paanalytics.net.
- Covered pandas topics: reading files, selecting and filtering, groupby, pivot_table, merging, and reshaping
- Machine learning modules include linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation
- Start or buy through the Hotmart checkout linked on the site
| Excel pivot table field | pivot_table argument | What it controls |
|---|---|---|
| Rows | index | The field or list of fields that become the row labels; the list order sets the level order |
| Columns | columns | The field whose values spread across the top of the table |
| Values | values | The numeric column being summarized |
| Summarize Values By | aggfunc | The calculation applied inside each cell; defaults to mean, not sum |
| Grand Totals | margins=True | Adds the totals row and column, labeled by margins_name |
| Blank cells | fill_value | Replaces NaN in the output with the value you pass |
Field names and argument behavior come from the pandas pivot_table API; the pandas module of the Python for Data Science and Analytics course covers these parameters in practice.
Learn pandas from scratch, with an end-to-end final project
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Does pivot_table sum by default?
No. The default aggfunc is mean, so sales.pivot_table(index='region', values='amount') returns averages. Pass aggfunc='sum' to match the Sum default you see in Excel.
What is the difference between pivot and pivot_table?
pivot reshapes without aggregating, so it fails when an index and column pair repeats. pivot_table aggregates those repeats and also accepts aggfunc, fill_value, margins, and dropna, which is why it is the tool that reproduces an Excel pivot table.
How do I flatten MultiIndex columns after pivot_table?
Join the levels into one label, for example table.columns = ['_'.join(map(str, c)) for c in table.columns], then call reset_index() to move the row levels back into ordinary columns. Do this before exporting or merging.
Why is my pivot table empty or all NaN?
The values column is probably not numeric — currency symbols, commas as decimal separators, or numbers stored as text all produce NaN under sum and mean. Check sales.dtypes first, convert with pd.to_numeric, and use aggfunc='count' to confirm whether the records are actually there.
Do I need prior programming experience to use pandas pivot tables?
You do not need prior programming experience to start. pivot_table is four named arguments, and the Python for Data Science and Analytics course begins with IDE and Jupyter Notebook setup and basic functions before moving into NumPy and pandas, so the pandas material arrives after the fundamentals are in place.