diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c63bc5164e25b..921be7a63176d 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1171,10 +1171,18 @@ def std(self, ddof=1, *args, **kwargs): ddof : integer, default 1 degrees of freedom """ - - # TODO: implement at Cython level? nv.validate_groupby_func('std', args, kwargs) - return np.sqrt(self.var(ddof=ddof, **kwargs)) + if ddof == 1: + try: + return self._cython_agg_general('std', **kwargs) + except Exception: + f = lambda x: x.std(ddof=ddof, **kwargs) + with _group_selection_context(self): + return self._python_agg_general(f) + else: + f = lambda x: x.std(ddof=ddof, **kwargs) + with _group_selection_context(self): + return self._python_agg_general(f) @Substitution(name='groupby') @Appender(_common_see_also) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 1ae8efd2f6867..630ac883b40ca 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1698,3 +1698,35 @@ def test_groupby_agg_ohlc_non_first(): result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc']) tm.assert_frame_equal(result, expected) + + +def test_groupby_std_with_as_index_false(): + # https://github.com/pandas-dev/pandas/issues/16799 + + df = pd.DataFrame({ + "A": ["a", "b", "a", "b"], + "B": ["A", "B", "A", "B"], + "X": [1, 2, 3, 4] + }) + + group_var = df.groupby( + ["A", "B"], + as_index=False, + ).var() + + # A B X + # 0 a A 2 + # 1 b B 2 + + group_std = df.groupby( + ["A", "B"], + as_index=False, + ).std() + + # A B X + # 0 a A 1.414214 + # 1 b B 1.414214 + + assert_series_equal( + np.sqrt(group_var["X"]), + group_std["X"])