Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
^^^^^^
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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)
Expand Down