Skip to content

Commit 2a11e78

Browse files
author
Eric Kisslinger
committed
BUG: Fix groupby over a CategoricalIndex in axis=1
closes GH18432
1 parent 262e8ff commit 2a11e78

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pandas/core/groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2859,7 +2859,7 @@ def is_in_obj(gpr):
28592859
else:
28602860
in_axis, name = False, None
28612861

2862-
if is_categorical_dtype(gpr) and len(gpr) != len(obj):
2862+
if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]:
28632863
raise ValueError("Categorical dtype grouper must "
28642864
"have len(grouper) == len(data)")
28652865

pandas/tests/groupby/test_categorical.py

+19
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,25 @@ def test_groupby_categorical_index(self):
191191
[0, 1, 2, 3], levels, ordered=True), name='cats')
192192
assert_frame_equal(result, expected)
193193

194+
def test_groupby_categorical_columns_index(self):
195+
# GH18432
196+
columns = ['A', 'B', 'A', 'B']
197+
categories = ['B', 'A']
198+
data = np.random.rand(10, 4)
199+
cat_index = CategoricalIndex(columns,
200+
categories=categories,
201+
ordered=True)
202+
df = DataFrame(data, columns=cat_index)
203+
result = df.groupby(axis=1, level=0).sum()
204+
df = DataFrame(data, columns=columns)
205+
expected = df.groupby(axis=1, level=0).sum()
206+
expected = expected[categories]
207+
expected.columns = CategoricalIndex(categories,
208+
categories=categories,
209+
ordered=True)
210+
211+
assert_frame_equal(result, expected)
212+
194213
def test_groupby_describe_categorical_columns(self):
195214
# GH 11558
196215
cats = pd.CategoricalIndex(['qux', 'foo', 'baz', 'bar'],

0 commit comments

Comments
 (0)