The pivot table is a powerful tool to summarize and present data. Pandas has a function which allows you to quickly convert a DataFrame to a pivot table - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html
This function is very useful but sometimes it can be tricky to remember how to use it to get the data formatted in a way you need.
This notebook will walk through how to use the pivot_table.
The full blog post for this article is here - http://pbpython.com/pandas-pivot-table-explained.html
In [1]:
import pandas as pd
import numpy as np
Read in our sales funnel data into our DataFrame
In [2]:
df = pd.read_excel("../in/sales-funnel.xlsx")
df.head()
Out[2]:
For convenience sake, let's define the status column as a category and set the order we want to view.
This isn't strictly required but helps us keep the order we want as we work through analyzing the data.
In [3]:
df["Status"] = df["Status"].astype("category")
df["Status"].cat.set_categories(["won","pending","presented","declined"],inplace=True)
As we build up the pivot table, I think it's easiest to take it one step at a time. Add items one at a time and check each step to verify you are getting the results you expect.
The simplest pivot table must have a dataframe and an index. In this case, let's use the Name as our index.
In [4]:
pd.pivot_table(df,index=["Name"])
Out[4]:
You can have multiple indexes as well. In fact, most of the pivot_table args can take multiple values via a list.
In [5]:
pd.pivot_table(df,index=["Name","Rep","Manager"])
Out[5]:
This is interesting but not particularly useful. What we probably want to do is look at this by Manager and Director. It's easy enough to do by changing the index.
In [6]:
pd.pivot_table(df,index=["Manager","Rep"])
Out[6]:
You can see that the pivot table is smart enough to start aggregating the data and summarizing it by grouping the reps with their managers. Now we start to get a glimpse of what a pivot table can do for us.
For this purpose, the Account and Quantity columns aren't really useful. Let's remove it by explicitly defining the columns we care about using the values field.
In [7]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"])
Out[7]:
The price column automatically averages the data but we can do a count or a sum. Adding them is simple using aggfunc.
In [8]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=np.sum)
Out[8]:
aggfunc can take a list of functions. Let's try a mean using the numpy functions and len to get a count.
In [9]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],aggfunc=[np.mean,len])
Out[9]:
If we want to see sales broken down by the products, the columns variable allows us to define one or more columns.
In [10]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],
columns=["Product"],aggfunc=[np.sum])
Out[10]:
The NaN's are a bit distracting. If we want to remove them, we could use fill_value to set them to 0.
In [11]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price"],
columns=["Product"],aggfunc=[np.sum],fill_value=0)
Out[11]:
I think it would be useful to add the quantity as well. Add Quantity to the values list.
In [12]:
pd.pivot_table(df,index=["Manager","Rep"],values=["Price","Quantity"],
columns=["Product"],aggfunc=[np.sum],fill_value=0)
Out[12]:
What's interesting is that you can move items to the index to get a different visual representation. We can add the Products to the index.
In [13]:
pd.pivot_table(df,index=["Manager","Rep","Product"],
values=["Price","Quantity"],aggfunc=[np.sum],fill_value=0)
Out[13]:
For this data set, this representation makes more sense. Now, what if I want to see some totals? margins=True does that for us.
In [14]:
pd.pivot_table(df,index=["Manager","Rep","Product"],
values=["Price","Quantity"],
aggfunc=[np.sum,np.mean],fill_value=0,margins=True)
Out[14]:
Let's move the analysis up a level and look at our pipeline at the manager level. Notice how the status is ordered based on our earlier category definition.
In [15]:
pd.pivot_table(df,index=["Manager","Status"],values=["Price"],
aggfunc=[np.sum],fill_value=0,margins=True)
Out[15]:
A really handy feature is the ability to pass a dictionary to the aggfunc so you can perform different functions on each of the values you select. This has a side-effect of making the labels a little cleaner.
In [16]:
pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"],
aggfunc={"Quantity":len,"Price":np.sum},fill_value=0)
Out[16]:
You can provide a list of aggfunctions to apply to each value too:
In [17]:
table = pd.pivot_table(df,index=["Manager","Status"],columns=["Product"],values=["Quantity","Price"],
aggfunc={"Quantity":len,"Price":[np.sum,np.mean]},fill_value=0)
table
Out[17]:
It can look daunting to try to pull this all together at once but as soon as you start playing with the data and slowly add the items, you can get a feel for how it works.
Once you have generated your data, it is in a DataFrame so you can filter on it using your normal DataFrame functions.
In [18]:
table.query('Manager == ["Debra Henley"]')
Out[18]:
In [19]:
table.query('Status == ["pending","won"]')
Out[19]:
I hope this tutorial has shown you how to use pivot tables on your data sets.