Introduction
Pivot tables help you quickly summarize and explore data by grouping and calculating values in a simple table.
Pivot tables help you quickly summarize and explore data by grouping and calculating values in a simple table.
pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None)
data is your DataFrame.
index sets rows, columns sets columns, and values are the data to summarize.
df.pivot_table(values='Sales', index='Region', columns='Product', aggfunc='sum')
df.pivot_table(values='Score', index='Student', aggfunc='mean')
df.pivot_table(values='Amount', index='Date', aggfunc='count')
This code creates a table showing total sales for each product by region. Missing values are filled with 0.
import pandas as pd data = { 'Region': ['East', 'East', 'West', 'West', 'East'], 'Product': ['A', 'B', 'A', 'B', 'A'], 'Sales': [100, 150, 200, 250, 300] } df = pd.DataFrame(data) pivot = df.pivot_table(values='Sales', index='Region', columns='Product', aggfunc='sum', fill_value=0) print(pivot)
If some combinations have no data, use fill_value to replace missing values.
You can use different functions like sum, mean, or count with aggfunc.
Pivot tables group and summarize data easily.
Use index for rows and columns for columns.
Choose how to summarize with aggfunc.
index parameter do in the pivot_table() function?index in pivot_table()index parameter specifies which column(s) to use as the rows in the resulting pivot table.columns parameter sets the columns, aggfunc sets the aggregation, and filtering is done separately.index = rows [OK]pandas using pivot_table()?pd.pivot_table() with parameters index for rows and columns for columns.df below:Product Region Sales 0 A East 100 1 B East 150 2 A West 200 3 B West 250 4 A East 50 5 B West 100
pd.pivot_table(df, index='Product', columns='Region', values='Sales', aggfunc='sum')
pd.pivot_table(df, index='Product', columns='Region', values='Sales', aggfunc='average')
columns is correct, values can be a column name string, and index can be a string or list.Store, Product, Month, and Revenue. You want a pivot table showing total revenue per store for each product, but only for months January and February. Which code correctly creates this pivot table?df[df['Month'].isin(['January', 'February'])] to select only those months before pivoting.index='Store', columns='Product', and sum revenue with aggfunc='sum'.Pass the test and this pattern moves unknown