Skip to content

Commit 586bcb1

Browse files
charlesdong1991jreback
authored andcommitted
BUG: pivot_table with multi-index columns only fails (#31013)
1 parent 698920f commit 586bcb1

File tree

3 files changed

+18
-8
lines changed

3 files changed

+18
-8
lines changed

doc/source/whatsnew/v1.1.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ Reshaping
140140
^^^^^^^^^
141141

142142
-
143-
-
143+
- Bug in :meth:`DataFrame.pivot_table` when only MultiIndexed columns is set (:issue:`17038`)
144144

145145
Sparse
146146
^^^^^^

pandas/core/reshape/pivot.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,9 @@ def pivot_table(
117117
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
118118

119119
table = agged
120-
if table.index.nlevels > 1:
120+
121+
# GH17038, this check should only happen if index is defined (not None)
122+
if table.index.nlevels > 1 and index:
121123
# Related GH #17123
122124
# If index_names are integers, determine whether the integers refer
123125
# to the level position or name.

pandas/tests/reshape/test_pivot.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -896,12 +896,6 @@ def _check_output(
896896
totals = table.loc[("All", ""), value_col]
897897
assert totals == self.data[value_col].mean()
898898

899-
# no rows
900-
rtable = self.data.pivot_table(
901-
columns=["AA", "BB"], margins=True, aggfunc=np.mean
902-
)
903-
assert isinstance(rtable, Series)
904-
905899
table = self.data.pivot_table(index=["AA", "BB"], margins=True, aggfunc="mean")
906900
for item in ["DD", "EE", "FF"]:
907901
totals = table.loc[("All", ""), item]
@@ -951,6 +945,20 @@ def test_margins_dtype_len(self):
951945

952946
tm.assert_frame_equal(expected, result)
953947

948+
@pytest.mark.parametrize("cols", [(1, 2), ("a", "b"), (1, "b"), ("a", 1)])
949+
def test_pivot_table_multiindex_only(self, cols):
950+
# GH 17038
951+
df2 = DataFrame({cols[0]: [1, 2, 3], cols[1]: [1, 2, 3], "v": [4, 5, 6]})
952+
953+
result = df2.pivot_table(values="v", columns=cols)
954+
expected = DataFrame(
955+
[[4, 5, 6]],
956+
columns=MultiIndex.from_tuples([(1, 1), (2, 2), (3, 3)], names=cols),
957+
index=Index(["v"]),
958+
)
959+
960+
tm.assert_frame_equal(result, expected)
961+
954962
def test_pivot_integer_columns(self):
955963
# caused by upstream bug in unstack
956964

0 commit comments

Comments
 (0)