I am trying to create pivot tables for different locations from the following dataframe (df
):
Location | Category | Status | Price |
---|---|---|---|
1 | Furniture | New | $100 |
1 | Furniture | Old | $50 |
2 | Office Supplies | New | $200 |
1 | Furniture | New | $100 |
1 | Office Supplies | New | $300 |
1 | Office Supplies | Old | $150 |
First, I have filtered the dataframe to separate for location 1 & 2 with code:
df1 = df[df['Location'] == 1]
df2 = df[df['Location'] == 2]
Next I have used the standard pandas pivot table function:
pd.pivot_table(df1, values='Price', index='Status', columns='Category', aggfunc=np.sum)
pd.pivot_table(df2, values='Price', index='Status', columns='Category', aggfunc=np.sum)
So I have the following two pivot tables as output:
Location 1:
Status | Furniture | Office Supplies |
---|---|---|
New | $200 | $300 |
Old | $50 | $150 |
Location 2:
Status | Office Supplies |
---|---|
New | $200 |
However, I want the pivot table for location 2 to include all possible categories and statuses and have 0 if they are not present. To summarize, I want the following pivot table for location 2:
Location 2:
Status | Furniture | Office Supplies |
---|---|---|
New | $0 | $200 |
Old | $0 | $0 |
I have gone through all the options of the pivot_table() function, but haven't found anything to solve this so far.