diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 6d1f2afab3c6d..6c15c056fc7ce 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -441,7 +441,7 @@ Reshaping - Bug in :meth:`DataFrame.unstack` and :meth:`Series.unstack` unstacking wrong level of :class:`MultiIndex` when :class:`MultiIndex` has mixed names (:issue:`48763`) - Bug in :meth:`DataFrame.pivot` not respecting ``None`` as column name (:issue:`48293`) - Bug in :func:`join` when ``left_on`` or ``right_on`` is or includes a :class:`CategoricalIndex` incorrectly raising ``AttributeError`` (:issue:`48464`) -- +- Bug in :meth:`DataFrame.pivot_table` raising ``ValueError`` with parameter ``margins=True`` when result is an empty :class:`DataFrame` (:issue:`49240`) Sparse ^^^^^^ diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 8b49d681379c6..37e78c7dbf7a2 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -411,7 +411,11 @@ def _all_key(key): table_pieces.append(transformed_piece) margin_keys.append(all_key) - result = concat(table_pieces, axis=cat_axis) + if not table_pieces: + # GH 49240 + return table + else: + result = concat(table_pieces, axis=cat_axis) if len(rows) == 0: return result diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index b021b1aa97a0e..39ca2c1b75589 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2086,8 +2086,9 @@ def test_pivot_table_aggfunc_scalar_dropna(self, dropna): tm.assert_frame_equal(result, expected) - def test_pivot_table_empty_aggfunc(self): - # GH 9186 & GH 13483 + @pytest.mark.parametrize("margins", [True, False]) + def test_pivot_table_empty_aggfunc(self, margins): + # GH 9186 & GH 13483 & GH 49240 df = DataFrame( { "A": [2, 2, 3, 3, 2], @@ -2096,7 +2097,9 @@ def test_pivot_table_empty_aggfunc(self): "D": [None, None, None, None, None], } ) - result = df.pivot_table(index="A", columns="D", values="id", aggfunc=np.size) + result = df.pivot_table( + index="A", columns="D", values="id", aggfunc=np.size, margins=margins + ) expected = DataFrame(index=Index([], dtype="int64", name="A")) expected.columns.name = "D" tm.assert_frame_equal(result, expected)