Repository: pandas-dev/pandas
Pull request: pivot_table very slow on Categorical data; how about an observed keyword argument? #24923
- [x] closes #24923
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry


Problem statement:
pivot_table very slow on Categorical data; how about an observed keyword argument?
#### Code Sample, a copy-pastable example if possible

```python
In [1]: df = pd.DataFrame({'col1': list('abcde'), 'col2': list('fghij'), 'col3': [1, 2, 3, 4, 5]})                                                                                                                                                                                                                                 

In [1]: df.pivot_table(index='col1', values='col3', columns='col2', aggfunc=np.sum, fill_value=0)                                                                                                                                                                                                                                  
Out[1]: 
col2  f  g  h  i  j
col1               
a     1  0  0  0  0
b     0  2  0  0  0
c     0  0  3  0  0
d     0  0  0  4  0
e     0  0  0  0  5

In [2]: %timeit df.pivot_table(index='col1', values='col3', columns='col2', aggfunc=np.sum, fill_value=0)                                                                                                                                                                                                                         
5.56 ms ± 89.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [3]: df.col1 = df.col1.astype('category')                                                                                                                                                                                                                                                                                      

In [4]: df.col2 = df.col2.astype('category')                                                                                                                                                                                                                                                                                      

In [5]: %timeit df.pivot_table(index='col1', values='col3', columns='col2', aggfunc=np.sum, fill_value=0)                                                                                                                                                                                                                         
94.7 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)



```
#### Problem description

groupby has an observed keyword argument (which was added to speed up grouping with categorical data by avoiding cartesian cross-products).

Unfortunately, pivot_table does not have such an option, and since it ultimately calls groupby with observed=False in pivot.py, pivot tables ultimately can be extremely slow for categorical data.  Note the simple example above, which runs almost 20 times slower for categorical data (and it would be much worse if the categories were larger).

I believe by simply adding an observed=False keyword argument to pivot_table, the code will be backwards compatible, but then categorical data will be processed efficiently.

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.7.2.final.0
python-bits: 64
OS: Darwin
OS-release: 18.2.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: None
LOCALE: en_US.UTF-8

pandas: 0.23.4
pytest: None
pip: 18.1
setuptools: 40.6.2
Cython: None
numpy: 1.15.4
scipy: None
pyarrow: None
xarray: None
IPython: 7.2.0
sphinx: None
patsy: None
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: 1.2.0
xlwt: None
xlsxwriter: 1.1.2
lxml: None
bs4: 4.6.3
html5lib: None
sqlalchemy: 1.2.15
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.7.0

</details>

Hints from issue discussion:

Commit message: Added "an" to whatsnew and added example from original issue to the test - this checks passing observed parameter remains equivalent to not passing.

Patch to review:
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 5129449e4fdf3..334b520e6479e 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -19,7 +19,7 @@ including other versions of pandas.
 Other Enhancements
 ^^^^^^^^^^^^^^^^^^
 
--
+:meth:`DataFrame.pivot_table` now accepts an ``observed`` parameter which is passed to underlying calls to :meth:`DataFrame.groupby` to speed up grouping categorical data. (:issue:`24923`)
 -
 -
 
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b4f79bda25517..30621e39c17b8 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5669,6 +5669,13 @@ def pivot(self, index=None, columns=None, values=None):
         margins_name : string, default 'All'
             Name of the row / column that will contain the totals
             when margins is True.
+        observed : boolean, default False
+            This option is passed to calls to groupby.
+            This only applies if any of the groupers are Categoricals.
+            If True: only show observed values for categorical groupers.
+            If False: show all values for categorical groupers.
+
+            .. versionchanged :: 0.25.0
 
         Returns
         -------
@@ -5760,12 +5767,12 @@ def pivot(self, index=None, columns=None, values=None):
     @Appender(_shared_docs['pivot_table'])
     def pivot_table(self, values=None, index=None, columns=None,
                     aggfunc='mean', fill_value=None, margins=False,
-                    dropna=True, margins_name='All'):
+                    dropna=True, margins_name='All', observed=False):
         from pandas.core.reshape.pivot import pivot_table
         return pivot_table(self, values=values, index=index, columns=columns,
                            aggfunc=aggfunc, fill_value=fill_value,
                            margins=margins, dropna=dropna,
-                           margins_name=margins_name)
+                           margins_name=margins_name, observed=observed)
 
     def stack(self, level=-1, dropna=True):
         """
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index c7c447d18b6b1..1adaa8bc5cc1c 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -24,7 +24,7 @@
 @Appender(_shared_docs['pivot_table'], indents=1)
 def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
                 fill_value=None, margins=False, dropna=True,
-                margins_name='All'):
+                margins_name='All', observed=False):
     index = _convert_by(index)
     columns = _convert_by(columns)
 
@@ -35,7 +35,8 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
             table = pivot_table(data, values=values, index=index,
                                 columns=columns,
                                 fill_value=fill_value, aggfunc=func,
-                                margins=margins, margins_name=margins_name)
+                                margins=margins, margins_name=margins_name,
+                                observed=observed)
             pieces.append(table)
             keys.append(getattr(func, '__name__', func))
 
@@ -78,7 +79,7 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
                 pass
         values = list(values)
 
-    grouped = data.groupby(keys, observed=False)
+    grouped = data.groupby(keys, observed=observed)
     agged = grouped.agg(aggfunc)
     if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):
         agged = agged.dropna(how='all')
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index e4fbb204af533..f05466b8b8859 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -38,18 +38,18 @@ def setup_method(self, method):
                                'E': np.random.randn(11),
                                'F': np.random.randn(11)})
 
-    def test_pivot_table(self):
+    def test_pivot_table(self, observed):
         index = ['A', 'B']
         columns = 'C'
         table = pivot_table(self.data, values='D',
-                            index=index, columns=columns)
+                            index=index, columns=columns, observed=observed)
 
         table2 = self.data.pivot_table(
-            values='D', index=index, columns=columns)
+            values='D', index=index, columns=columns, observed=observed)
         tm.assert_frame_equal(table, table2)
 
         # this works
-        pivot_table(self.data, values='D', index=index)
+        pivot_table(self.data, values='D', index=index, observed=observed)
 
         if len(index) > 1:
             assert table.index.names == tuple(index)
@@ -65,6 +65,23 @@ def test_pivot_table(self):
             index + [columns])['D'].agg(np.mean).unstack()
         tm.assert_frame_equal(table, expected)
 
+        df = pd.DataFrame({'col1': list('abcde'),
+                           'col2': list('fghij'),
+                           'col3': [1, 2, 3, 4, 5]})
+
+        df.col1 = df.col1.astype('category')
+        df.col2 = df.col1.astype('category')
+
+        df_pivot = df.pivot_table(index='col1', values='col3',
+                                  columns='col2', aggfunc=np.sum,
+                                  fill_value=0)
+
+        df_pivot_observed = df.pivot_table(index='col1', values='col3',
+                                           columns='col2', aggfunc=np.sum,
+                                           fill_value=0, observed=observed)
+
+        tm.assert_frame_equal(df_pivot, df_pivot_observed)
+
     def test_pivot_table_nocols(self):
         df = DataFrame({'rows': ['a', 'b', 'c'],
                         'cols': ['x', 'y', 'z'],


Code review comments:
diff_hunk: @@ -5669,6 +5669,13 @@ def pivot(self, index=None, columns=None, values=None):
         margins_name : string, default 'All'
             Name of the row / column that will contain the totals
             when margins is True.
+        observed : boolean, default False
+            This option is passed to calls to groupby.
path: pandas/core/frame.py
text: @user1:
you don't need the first sentence;

diff_hunk: @@ -65,6 +65,23 @@ def test_pivot_table(self):
             index + [columns])['D'].agg(np.mean).unstack()
         tm.assert_frame_equal(table, expected)
 
+        df = pd.DataFrame({'col1': list('abcde'),
path: pandas/tests/reshape/test_pivot.py
text: @user1:
this example should be parameterized on the observed kw as well.

diff_hunk: @@ -65,6 +65,23 @@ def test_pivot_table(self):
             index + [columns])['D'].agg(np.mean).unstack()
         tm.assert_frame_equal(table, expected)
 
+        df = pd.DataFrame({'col1': list('abcde'),
+                           'col2': list('fghij'),
+                           'col3': [1, 2, 3, 4, 5]})
+
+        df.col1 = df.col1.astype('category')
+        df.col2 = df.col1.astype('category')
+
+        df_pivot = df.pivot_table(index='col1', values='col3',
+                                  columns='col2', aggfunc=np.sum,
+                                  fill_value=0)
+
+        df_pivot_observed = df.pivot_table(index='col1', values='col3',
+                                           columns='col2', aggfunc=np.sum,
+                                           fill_value=0, observed=observed)
+
+        tm.assert_frame_equal(df_pivot, df_pivot_observed)
path: pandas/tests/reshape/test_pivot.py
text: @user1:
use result= and expected=