To pivot on two variables, you can pass a list of variables to the index or columns parameter in the pivot_table() method. 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 and profit data by region and monthpivot = pd.pivot_table(df, values=['Sales', 'Profit'], index=['Region', 'Month'], columns=['Salesperson'], aggfunc='sum')print(pivot) |
This will create a pivot table that summarizes the sales and profit data by region and month. The resulting output will be:
Profit Sales Salesperson Alice Bob Charlie Dave Eve Frank Alice Bob Charlie Dave Eve FrankRegion Month North Feb 50.0 200 NaN NaN NaN NaN 200 200 NaN NaN NaN NaN Jan 20.0 100 NaN NaN NaN NaN 100 200 NaN NaN NaN NaNSouth Feb NaN NaN 10.0 50 NaN NaN NaN NaN 50.0 50 NaN NaN Jan NaN NaN 30.0 NaN NaN NaN NaN NaN 150.0 NaN NaN NaNWest Feb NaN NaN NaN NaN 25 25 NaN NaN NaN NaN 75 125 Jan NaN NaN NaN NaN 15 NaN NaN NaN NaN NaN 75 NaN |
The resulting pivot table shows the total sales and profit for each salesperson broken down by region and month. The index parameter is passed a list of variables that specifies the rows to group by, and the columns parameter is passed a variable that specifies the columns to group by. You can pass any number of variables to group by to the index and columns parameters.