You can fill missing values in a pivot table using the fill_value parameter in the pivot_table() method. The fill_value parameter specifies the value to use when replacing missing values in the pivot table.
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'], columns=['Month', 'Salesperson'], aggfunc='sum', fill_value=0)print(pivot) |
This will create a pivot table that summarizes the sales and profit data by region and month, with missing values filled in with zeros. The resulting output will be:
Profit Sales Month Feb Jan Feb Jan Salesperson Bob Frank Dave Alice Eve Charlie Bob Frank Dave Alice EveRegion North 50.0 0 0 20.0 0 0 200 0 0 100 0South 10.0 0 50 0.0 0 30 0 0 150 0 0West 0.0 25 0 0.0 25 0 0 125 0 0 75 |
In this example, the fill_value parameter is set to zero. This causes any missing values in the pivot table to be filled with zeros. You can use any value you like for the fill_value parameter.