Skip to content

Commit d4bb7f6

Browse files
committed
BUG: pivot_table someitmes returns Series (pandas-dev#4386)
BUG: pivot_table sometimes returns Series (pandas-dev#4386) BUG: pivot_table sometimes returns Series (pandas-dev#4386)
1 parent 98de1d3 commit d4bb7f6

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

pandas/tools/pivot.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
7878
"""
7979
index = _convert_by(index)
8080
columns = _convert_by(columns)
81-
8281
if isinstance(aggfunc, list):
8382
pieces = []
8483
keys = []
@@ -164,7 +163,8 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
164163
margins_name=margins_name)
165164

166165
# discard the top level
167-
if values_passed and not values_multi and not table.empty:
166+
if values_passed and not values_multi and not table.empty and \
167+
(table.columns.nlevels > 1):
168168
table = table[values[0]]
169169

170170
if len(index) == 0 and len(columns) > 0:

pandas/tools/tests/test_pivot.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -350,13 +350,13 @@ def _check_output(result, values_col, index=['A', 'B'],
350350
# no rows
351351
rtable = self.data.pivot_table(columns=['AA', 'BB'], margins=True,
352352
aggfunc=np.mean)
353-
tm.assertIsInstance(rtable, DataFrame)
354-
355-
table = self.data.pivot_table(index=['AA', 'BB'], margins=True,
356-
aggfunc='mean')
357-
for item in ['DD', 'EE', 'FF']:
358-
totals = table.loc[('All', ''), item]
359-
self.assertEqual(totals, self.data[item].mean())
353+
expected = self.data.groupby(['AA','BB']).mean()
354+
expected.loc[('All', ''), :] = self.data[['DD', 'EE', 'FF']].mean()
355+
expected = (expected.stack()
356+
.unstack(['BB', 'AA'])
357+
.stack(['AA', 'BB'])
358+
.to_frame())
359+
tm.assert_frame_equal(expected, rtable)
360360

361361
# issue number #8349: pivot_table with margins and dictionary aggfunc
362362
data = [
@@ -485,8 +485,11 @@ def test_margins_no_values_no_cols(self):
485485
# Regression test on pivot table: no values or cols passed.
486486
result = self.data[['A', 'B']].pivot_table(
487487
index=['A', 'B'], aggfunc=len, margins=True)
488-
result_list = result.values.flatten().tolist()
489-
self.assertEqual(sum(result_list[:-1]), result_list[-1])
488+
expected = self.data[['A', 'B']].groupby(['A', 'B']).apply(len)
489+
expected.loc[('All', '')] = expected.sum()
490+
expected = expected.to_frame()
491+
492+
tm.assert_frame_equal(result, expected)
490493

491494
def test_margins_no_values_two_rows(self):
492495
# Regression test on pivot table: no values passed but rows are a

0 commit comments

Comments
 (0)