How to Create Pivot Table in Python

A pivot table is a powerful data analysis tool for summarizing large datasets. It helps you understand how your business is doing and can also be used to answer specific questions about your data. In python, you can create a pivot table with the pandas.pivot_table function, which is similar to those in spreadsheet tools like Microsoft Excel.
The Pandas pivot table function takes a DataFrame and the parameters that determine how the DataFrame should be summarized. The resulting pivot table can be outputted in the form of a spreadsheet with summarized data.
Step 1. Add Columns
First, you must decide how you want to organize the data you have. For example, if you are tracking your company’s sales, you might want to group sales by region or product. Once you have determined how your data will be organized, drag and drop a field into the Values area of the Pivot Table.
Once the field is in this area, it will be updated with the relevant data. For instance, if you have the sales data for different regions and you are organizing it by region, dragging the region name to this area will update the pivot table with the total sales for that region.
Step 2. Row Labels
A row label determines which rows (records) will be shown in the resulting Pivot Table. If you are organizing your sales data by sales person, dragging the “Salesperson” field to this area will filter the resulting table so that only those records with the “Salesperson” column in the output table will show up.
Step 3. Values
Once you have added a field, you will see it appear in the pivot table’s top box as a list of values. Click on a value to view its summary information, or select a different one to prompt the pivot table to do something with that specific value.
You can also change the order in which values appear, or display them differently. For example, you might want to show your product sales as percentages of the total. You can do that by right-clicking the cell carrying the sales figure and selecting Show Values As > % of Grand Total.
Step 4. Areas and Filters
Once your data is sorted, you can begin analyzing it using the areas and filters section of the Pivot Table. The fields in the areas section represent a summary of each group’s data, and the fields in the filters section are used to further filter down your results.
Step 5. Report Filter
If you have a lot of different columns of data and are trying to organize them into a logical order, you can use the Report Filter section of the Pivot Table. If you are organizing a table by color, you can add the “Color of Item” field to this section and the resulting table will be constructed with a report filter above the data, with drop-down options (Black, Red, and White in this example).
The final step is adding a summary of all the values for each group in the results. You can add a number, a percentage, or some other value to the values in the results to get a complete picture of your data.