diff --git a/doc/source/whatsnew/v0.18.0.txt b/doc/source/whatsnew/v0.18.0.txt index 75a38544fb8eb..67585d156a090 100644 --- a/doc/source/whatsnew/v0.18.0.txt +++ b/doc/source/whatsnew/v0.18.0.txt @@ -540,3 +540,4 @@ of columns didn't match the number of series provided (:issue:`12039`). - Bug in ``.loc`` setitem indexer preventing the use of a TZ-aware DatetimeIndex (:issue:`12050`) - Big in ``.style`` indexes and multi-indexes not appearing (:issue:`11655`) +- Bug in ``.pivot_table()`` where ``dropna`` argument drops columns and index level names (:issue:`12133`) diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py index 7a04847947bf2..0852d0114d697 100644 --- a/pandas/tools/pivot.py +++ b/pandas/tools/pivot.py @@ -126,13 +126,15 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', if not dropna: try: - m = MultiIndex.from_arrays(cartesian_product(table.index.levels)) + m = MultiIndex.from_arrays(cartesian_product(table.index.levels), + names=table.index.names) table = table.reindex_axis(m, axis=0) except AttributeError: pass # it's a single level try: - m = MultiIndex.from_arrays(cartesian_product(table.columns.levels)) + m = MultiIndex.from_arrays(cartesian_product(table.columns.levels), + names=table.columns.names) table = table.reindex_axis(m, axis=1) except AttributeError: pass # it's a single level or a series diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py index d303f489d9dea..93d4802b7d622 100644 --- a/pandas/tools/tests/test_pivot.py +++ b/pandas/tools/tests/test_pivot.py @@ -96,6 +96,18 @@ def test_pivot_table_dropna(self): assert_equal(pv_col.columns.values, m.values) assert_equal(pv_ind.index.values, m.values) + #issue 12133, dropna=False arg drops index level names + idx = pd.MultiIndex.from_tuples([(1000000, 201308), (1000000, 201310)], + names=('quantity', 'month')) + tup = (("B", "c"), ("B", "d"), ("C", "c"), ("C", "d")) + clm = pd.MultiIndex.from_tuples(tup, names=('customer', 'product')) + pv = pd.DataFrame([[50000, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, 30000]], + index=idx, columns=clm) + pv_gen = df[2:].pivot_table('amount', ['quantity', 'month'], + ['customer', 'product'], dropna=False) + tm.assert_frame_equal(pv, pv_gen) + def test_pass_array(self): result = self.data.pivot_table( 'D', index=self.data.A, columns=self.data.C)