Skip to content

Commit b906317

Browse files
author
Nicolai Reeve
committed
BUG: fixed issue with mixed type groupby aggregate
Fixes issue pandas-dev#16916, where using aggregate on a mixed type grouping vector fails. Added test in test_aggregate.py to ensure that the bug is fixed.
1 parent 6000c5b commit b906317

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

pandas/core/groupby.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -2883,7 +2883,12 @@ def aggregate(self, func_or_funcs, *args, **kwargs):
28832883
except Exception:
28842884
result = self._aggregate_named(func_or_funcs, *args, **kwargs)
28852885

2886-
index = Index(sorted(result), name=self.grouper.names[0])
2886+
# mixed types fail to sort
2887+
try:
2888+
values = sorted(result)
2889+
except TypeError:
2890+
values = result
2891+
index = Index(values, name=self.grouper.names[0])
28872892
ret = Series(result, index=index)
28882893

28892894
if not self.as_index: # pragma: no cover

pandas/tests/groupby/test_aggregate.py

+11
Original file line numberDiff line numberDiff line change
@@ -892,3 +892,14 @@ def test_sum_uint64_overflow(self):
892892
expected.index.name = 0
893893
result = df.groupby(0).sum()
894894
tm.assert_frame_equal(result, expected)
895+
896+
def test_mixed_type_grouping(self):
897+
X = pd.DataFrame(data=[[[1,1],[2,2],[3,3]], [[1,1],[2,2],[3,3]]],
898+
columns=['X', 'Y', 'Z'],
899+
index=pd.Index(data=[ 2,'g1'], name='grouping'))
900+
901+
S = pd.DataFrame(data=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]],
902+
columns=list('XYZ'), index=list('qwer'))
903+
S['grouping'] = ['g1', 'g1', 2, 2]
904+
T = S.groupby('grouping').aggregate(lambda x: x.tolist())
905+
tm.assert_frame_equal(T, X)

0 commit comments

Comments
 (0)