Repository: pandas-dev/pandas

Issue:
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>



Discussion:

Resolving patch:
diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py
--- a/asv_bench/benchmarks/reshape.py
+++ b/asv_bench/benchmarks/reshape.py
@@ -127,6 +127,10 @@ def setup(self):
                              'value1': np.random.randn(N),
                              'value2': np.random.randn(N),
                              'value3': np.random.randn(N)})
+        self.df2 = DataFrame({'col1': list('abcde'), 'col2': list('fghij'),
+                              'col3': [1, 2, 3, 4, 5]})
+        self.df2.col1 = self.df2.col1.astype('category')
+        self.df2.col2 = self.df2.col2.astype('category')
 
     def time_pivot_table(self):
         self.df.pivot_table(index='key1', columns=['key2', 'key3'])
@@ -139,6 +143,14 @@ def time_pivot_table_margins(self):
         self.df.pivot_table(index='key1', columns=['key2', 'key3'],
                             margins=True)
 
+    def time_pivot_table_categorical(self):
+        self.df2.pivot_table(index='col1', values='col3', columns='col2',
+                             aggfunc=np.sum, fill_value=0)
+
+    def time_pivot_table_categorical_observed(self):
+        self.df2.pivot_table(index='col1', values='col3', columns='col2',
+                             aggfunc=np.sum, fill_value=0, observed=True)
+
 
 class Crosstab:
 
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5701,6 +5701,12 @@ 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 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
         -------
@@ -5791,12 +5797,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
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -22,7 +22,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)
 
@@ -34,7 +34,8 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
                                 columns=columns,
                                 fill_value=fill_value, aggfunc=func,
                                 margins=margins, dropna=dropna,
-                                margins_name=margins_name)
+                                margins_name=margins_name,
+                                observed=observed)
             pieces.append(table)
             keys.append(getattr(func, '__name__', func))
 
@@ -77,7 +78,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')


Test patch:
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -37,18 +37,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)
@@ -64,6 +64,28 @@ def test_pivot_table(self):
             index + [columns])['D'].agg(np.mean).unstack()
         tm.assert_frame_equal(table, expected)
 
+    def test_pivot_table_categorical_observed_equal(self, observed):
+        # issue #24923
+        df = pd.DataFrame({'col1': list('abcde'),
+                           'col2': list('fghij'),
+                           'col3': [1, 2, 3, 4, 5]})
+
+        expected = df.pivot_table(index='col1', values='col3',
+                                  columns='col2', aggfunc=np.sum,
+                                  fill_value=0)
+
+        expected.index = expected.index.astype('category')
+        expected.columns = expected.columns.astype('category')
+
+        df.col1 = df.col1.astype('category')
+        df.col2 = df.col2.astype('category')
+
+        result = df.pivot_table(index='col1', values='col3',
+                                columns='col2', aggfunc=np.sum,
+                                fill_value=0, observed=observed)
+
+        tm.assert_frame_equal(result, expected)
+
     def test_pivot_table_nocols(self):
         df = DataFrame({'rows': ['a', 'b', 'c'],
                         'cols': ['x', 'y', 'z'],