You can sum values in a pivot table by specifying the aggfunc parameter in the pivot_table() method as 'sum'. This will create a pivot table that summarizes the data by grouping and summing values based on the specified rows, columns, and values.
Here's an example:
import pandas as pd# create a pandas DataFramedf = pd.DataFrame({'Region': ['North', 'North', 'South', 'South', 'West', 'West'], 'Month': ['Jan', 'Feb', 'Jan', 'Feb', 'Jan', 'Feb'], 'Salesperson': ['Alice', 'Bob', 'Charlie', 'Dave', 'Eve', 'Frank'], 'Sales': [100, 200, 150, 50, 75, 125], 'Profit': [20, 50, 30, 10, 15, 25]})# create a pivot table that summarizes the sales data by region and monthpivot = pd.pivot_table(df, values=['Sales'], index=['Region'], columns=['Month'], aggfunc='sum')print(pivot) |
This will create a pivot table that summarizes the sales data by region and month, with values grouped and summed. The resulting output will be:
Sales Month Feb JanRegion North 200 100South 50 150West 200 75 |
In this example, the aggfunc parameter is set to 'sum', which causes the values in the pivot table to be summed based on the specified rows and columns. You can use other aggregation functions such as 'mean', 'min', 'max', or a custom function by passing the desired function name or function object to the aggfunc parameter.