You can convert a pandas groupby object into a pivot table using the pivot_table() method in pandas. Here's an example:
import pandas as pd# create a pandas DataFramedf = pd.DataFrame({'Region': ['North', 'North', 'South', 'South', 'West', 'West'], 'Salesperson': ['Alice', 'Bob', 'Charlie', 'Dave', 'Eve', 'Frank'], 'Sales': [100, 200, 150, 50, 75, 125]})# group by region and salesperson and calculate the total sales for each groupgrouped = df.groupby(['Region', 'Salesperson']).sum()# convert the groupby object to a pivot tablepivot = grouped.pivot_table(values='Sales', index=['Region'], columns=['Salesperson'], aggfunc=sum)print(pivot) |
This will group the DataFrame by region and salesperson and calculate the total sales for each group. Then, the pivot_table() method is used to convert the resulting groupby object into a pivot table that shows the total sales for each salesperson broken down by region. The resulting output will be the same as the previous example:
|
Salesperson Alice Bob Charlie Dave Eve Frank
Region
North 100 200 NaN NaN NaN NaN
South NaN NaN 150.0 50.0 NaN NaN
West NaN NaN NaN NaN 75.0 125.0
|
pivot_table() method are similar to those used in the previous example. The values parameter specifies the column to summarize (in this case, 'Sales'), the index parameter specifies the rows to group by (in this case, 'Region'), and the columns parameter specifies the columns to group by (in this case, 'Salesperson'). The aggfunc parameter specifies the function to use to summarize the data (in this case, sum(), which is the default function).