Skip to content

Commit d998337

Browse files
jakevdpjreback
authored andcommitted
BUG: quick fix for pandas-dev#10989
TST: add test case from Issue pandas-dev#10989
1 parent 5d953e3 commit d998337

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

pandas/tools/pivot.py

+14
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,20 @@ def _add_margins(table, data, values, rows, cols, aggfunc):
159159

160160
grand_margin = _compute_grand_margin(data, values, aggfunc)
161161

162+
# categorical index or columns will fail below when 'All' is added
163+
# here we'll convert all categorical indices to object
164+
def convert_categorical(ind):
165+
_convert = lambda ind: (ind.astype('object')
166+
if ind.dtype.name == 'category' else ind)
167+
if isinstance(ind, MultiIndex):
168+
return ind.set_levels([_convert(lev) for lev in ind.levels])
169+
else:
170+
return _convert(ind)
171+
172+
table.index = convert_categorical(table.index)
173+
if hasattr(table, 'columns'):
174+
table.columns = convert_categorical(table.columns)
175+
162176
if not values and isinstance(table, Series):
163177
# If there are no values and the table is a series, then there is only
164178
# one column in the data. Compute grand margin and return it.

pandas/tools/tests/test_pivot.py

+14
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,20 @@ def test_crosstab_dropna(self):
719719
('two', 'dull'), ('two', 'shiny')])
720720
assert_equal(res.columns.values, m.values)
721721

722+
def test_categorical_margins(self):
723+
# GH 10989
724+
data = pd.DataFrame({'x': np.arange(8),
725+
'y': np.arange(8) // 4,
726+
'z': np.arange(8) % 2})
727+
data.y = data.y.astype('category')
728+
data.z = data.z.astype('category')
729+
table = data.pivot_table('x', 'y', 'z', margins=True)
730+
assert_equal(table.values, [[1, 2, 1.5],
731+
[5, 6, 5.5],
732+
[3, 4, 3.5]])
733+
734+
735+
722736
if __name__ == '__main__':
723737
import nose
724738
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],

0 commit comments

Comments
 (0)