diff --git a/doc/source/whatsnew/v0.20.2.txt b/doc/source/whatsnew/v0.20.2.txt index 676da5c370041..9f88d629880ed 100644 --- a/doc/source/whatsnew/v0.20.2.txt +++ b/doc/source/whatsnew/v0.20.2.txt @@ -88,6 +88,7 @@ Groupby/Resample/Rolling - Bug creating datetime rolling window on an empty DataFrame (:issue:`15819`) - Bug in ``rolling.cov()`` with offset window (:issue:`16058`) +- Bug in ``.resample()`` and ``.groupby()`` when aggregating on integers (:issue:`16361`) Sparse diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 91b55c414b507..286677d613484 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3337,13 +3337,15 @@ def _cython_agg_blocks(self, how, alt=None, numeric_only=True): obj = self.obj[data.items[locs]] s = groupby(obj, self.grouper) result = s.aggregate(lambda x: alt(x, axis=self.axis)) - result = result._data.blocks[0] + newb = result._data.blocks[0] - # see if we can cast the block back to the original dtype - result = block._try_coerce_and_cast_result(result) + finally: + + # see if we can cast the block back to the original dtype + result = block._try_coerce_and_cast_result(result) + newb = block.make_block(result) new_items.append(locs) - newb = block.make_block_same_class(result) new_blocks.append(newb) if len(new_blocks) == 0: diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 170cab4947a5a..959e3d2f459ce 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -1672,6 +1672,28 @@ def test_resample_dtype_preservation(self): result = df.groupby('group').resample('1D').ffill() assert result.val.dtype == np.int32 + def test_resample_dtype_coerceion(self): + + pytest.importorskip('scipy') + + # GH 16361 + df = {"a": [1, 3, 1, 4]} + df = pd.DataFrame( + df, index=pd.date_range("2017-01-01", "2017-01-04")) + + expected = (df.astype("float64") + .resample("H") + .mean() + ["a"] + .interpolate("cubic") + ) + + result = df.resample("H")["a"].mean().interpolate("cubic") + tm.assert_series_equal(result, expected) + + result = df.resample("H").mean()["a"].interpolate("cubic") + tm.assert_series_equal(result, expected) + def test_weekly_resample_buglet(self): # #1327 rng = date_range('1/1/2000', freq='B', periods=20)