Pivot data
Summarize your data using pivot tables with totals, counts, and averages.
Example Data
Follow along with right out of the box example data. Copy following data in the information request of the agent you are working in.
Pivoting helps you turn rows into summaries. It's how we answer practical questions, such as:
"How much was sold by country and type?" or "How many services did each seller provide?" In Excel, users create pivot tables by dragging fields into rows, columns, and values. In Python, we use the pivot_table()
method to achieve the same — just more precisely and repeatably.
This section shows you how to create powerful summaries by combining groupings with calculations like sum, count, and average.
Create a basic pivot table
Excel
In Excel, you insert a pivot table and drag "Seller Country" into rows, and "Amount" into values (summed).
t0 Prompt
Create a pivot table with seller country as rows
Show total amount by seller country
Group amounts by country
Code
The python code looks as follows:
Add multiple statistics
Excel
In Excel, you can show both sum and average for the same field by dragging "Amount" in twice.
t0 Prompt
Show both sum and average amount per transaction type
Give me multiple stats in a pivot
Total and average grouped by colum Type
Code
The python code looks as follows:
Pivot with rows and columns
Excel
In Excel, you drag "Seller Country" into rows and "Transaction" into columns, then summarize values by sum or count.
t0 Prompt
Compare transaction types across countries
Create a pivot with country rows and type columns
Show totals by country and seller
Code
The python code looks as follows:
Function / Function Argument | Description |
---|---|
df.pivot_table() | Creates a pivot table from the data |
index= | Field to group by in rows |
columns= | Field to spread across columns |
values= | Field to summarize (e.g. Amount) |
aggfunc= | Aggregation method: "sum" , "mean" , "count" |
fill_value= | Optional: fills missing values with 0 or blank |