diff --git a/doc/source/whatsnew/v0.18.1.txt b/doc/source/whatsnew/v0.18.1.txt index c6642c5216262..8700bf1be8cfb 100644 --- a/doc/source/whatsnew/v0.18.1.txt +++ b/doc/source/whatsnew/v0.18.1.txt @@ -325,3 +325,4 @@ Bug Fixes - ``pd.read_excel()`` now accepts column names associated with keyword argument ``names``(:issue `12870`) - Bug in ``fill_value`` is ignored if the argument to a binary operator is a constant (:issue `12723`) +- Bug in ``groupby`` where complex types are coerced to float (:issue:`12902`) diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 6996254f58f00..e2a4482404506 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -1747,7 +1747,7 @@ def _cython_operation(self, kind, values, how, axis): values = _algos.ensure_float64(values) elif com.is_integer_dtype(values): values = values.astype('int64', copy=False) - elif is_numeric: + elif is_numeric and not com.is_complex_dtype(values): values = _algos.ensure_float64(values) else: values = values.astype(object) diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index 6cf779bad1a41..c18039f421455 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -2475,6 +2475,15 @@ def test_groupby_level_0_nonmulti(self): result = a.groupby(level=0).sum() self.assertEqual(result.index.name, a.index.name) + def test_groupby_complex(self): + # GH 12902 + a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) + result0 = a.groupby(level=0).sum() + result1 = a.sum(level=0) + expected = Series((1 + 2j, 5 + 10j)) + assert_series_equal(result0, expected) + assert_series_equal(result1, expected) + def test_level_preserve_order(self): grouped = self.mframe.groupby(level=0) exp_labels = np.array([0, 0, 0, 1, 1, 2, 2, 3, 3, 3])