Complete the code to create a pivot table that summarizes the average sales by region.
import pandas as pd data = {'Region': ['East', 'West', 'East', 'West'], 'Sales': [250, 150, 200, 300]} df = pd.DataFrame(data) pivot = df.pivot_table(values='Sales', index=[1]) print(pivot)
The index parameter specifies the column to group by. Here, we group sales by 'Region'.
Complete the code to create a pivot table that calculates the sum of sales for each product category.
data = {'Category': ['A', 'B', 'A', 'B'], 'Sales': [100, 200, 150, 300]}
df = pd.DataFrame(data)
pivot = df.pivot_table(values='Sales', index='Category', aggfunc=[1])
print(pivot)The aggfunc parameter defines how to aggregate the data. To get total sales, use 'sum'.
Fix the error in the code to create a pivot table that shows average sales by region and product.
data = {'Region': ['East', 'East', 'West', 'West'], 'Product': ['A', 'B', 'A', 'B'], 'Sales': [100, 150, 200, 250]}
df = pd.DataFrame(data)
pivot = df.pivot_table(values='Sales', index=['Region', [1]])
print(pivot)The index parameter can take a list of columns to group by multiple keys. Here, we add 'Product' to group sales by both region and product.
Fill both blanks to create a pivot table that counts the number of sales entries for each region and product.
data = {'Region': ['North', 'South', 'North', 'South'], 'Product': ['X', 'X', 'Y', 'Y'], 'Sales': [10, 20, 30, 40]}
df = pd.DataFrame(data)
pivot = df.pivot_table(index=[1], columns=[2], aggfunc='count')
print(pivot)The index groups rows, and columns groups columns. To count sales entries by region and product, use 'Region' for index and 'Product' for columns.
Fill all three blanks to create a pivot table that shows the maximum sales for each region and product, and rename the resulting column to 'MaxSales'.
data = {'Region': ['East', 'East', 'West', 'West'], 'Product': ['A', 'B', 'A', 'B'], 'Sales': [120, 180, 160, 200]}
df = pd.DataFrame(data)
pivot = df.pivot_table(index=[1], columns=[2], values=[3], aggfunc='max')
pivot.columns.name = 'Product'
pivot.rename(columns=lambda x: x, inplace=True)
pivot.columns = pivot.columns.rename('MaxSales')
print(pivot)To summarize max sales by region and product, set index='Region', columns='Product', and values='Sales'.