Skip to content

Commit 27b7579

Browse files
debnathshohamphofl
authored andcommitted
BUG: pivot_table with margins=T raises when results in empty df (pandas-dev#49438)
* BUG: pivot_table with margins=T raises when results in empty df * suggested change * suggested change * Update pivot.py * linked test to issue * suggested edit
1 parent 148f7ab commit 27b7579

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

doc/source/whatsnew/v2.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ Reshaping
456456
- Bug in :meth:`DataFrame.unstack` and :meth:`Series.unstack` unstacking wrong level of :class:`MultiIndex` when :class:`MultiIndex` has mixed names (:issue:`48763`)
457457
- Bug in :meth:`DataFrame.pivot` not respecting ``None`` as column name (:issue:`48293`)
458458
- Bug in :func:`join` when ``left_on`` or ``right_on`` is or includes a :class:`CategoricalIndex` incorrectly raising ``AttributeError`` (:issue:`48464`)
459-
-
459+
- Bug in :meth:`DataFrame.pivot_table` raising ``ValueError`` with parameter ``margins=True`` when result is an empty :class:`DataFrame` (:issue:`49240`)
460460

461461
Sparse
462462
^^^^^^

pandas/core/reshape/pivot.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,11 @@ def _all_key(key):
411411
table_pieces.append(transformed_piece)
412412
margin_keys.append(all_key)
413413

414-
result = concat(table_pieces, axis=cat_axis)
414+
if not table_pieces:
415+
# GH 49240
416+
return table
417+
else:
418+
result = concat(table_pieces, axis=cat_axis)
415419

416420
if len(rows) == 0:
417421
return result

pandas/tests/reshape/test_pivot.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -2086,8 +2086,9 @@ def test_pivot_table_aggfunc_scalar_dropna(self, dropna):
20862086

20872087
tm.assert_frame_equal(result, expected)
20882088

2089-
def test_pivot_table_empty_aggfunc(self):
2090-
# GH 9186 & GH 13483
2089+
@pytest.mark.parametrize("margins", [True, False])
2090+
def test_pivot_table_empty_aggfunc(self, margins):
2091+
# GH 9186 & GH 13483 & GH 49240
20912092
df = DataFrame(
20922093
{
20932094
"A": [2, 2, 3, 3, 2],
@@ -2096,7 +2097,9 @@ def test_pivot_table_empty_aggfunc(self):
20962097
"D": [None, None, None, None, None],
20972098
}
20982099
)
2099-
result = df.pivot_table(index="A", columns="D", values="id", aggfunc=np.size)
2100+
result = df.pivot_table(
2101+
index="A", columns="D", values="id", aggfunc=np.size, margins=margins
2102+
)
21002103
expected = DataFrame(index=Index([], dtype="int64", name="A"))
21012104
expected.columns.name = "D"
21022105
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)