Skip to content

Commit 330e557

Browse files
committed
Subclassed pct_change for SeriesGroupBy
1 parent 9c7c486 commit 330e557

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

pandas/core/groupby.py

+7
Original file line numberDiff line numberDiff line change
@@ -3901,6 +3901,13 @@ def _apply_to_column_groupbys(self, func):
39013901
""" return a pass thru """
39023902
return func(self)
39033903

3904+
def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None):
3905+
"""Calculate percent change of each value to previous entry in group"""
3906+
filled = getattr(self, fill_method)(limit=limit)
3907+
shifted = filled.shift(periods=periods, freq=freq)
3908+
3909+
return (filled / shifted) - 1
3910+
39043911

39053912
class NDFrameGroupBy(GroupBy):
39063913

pandas/tests/groupby/test_groupby.py

+18-7
Original file line numberDiff line numberDiff line change
@@ -2141,25 +2141,36 @@ def test_groupby_bool_aggs(self, agg_func, skipna, vals):
21412141
result = getattr(df.groupby('key'), agg_func)(skipna=skipna)
21422142
assert_frame_equal(result, exp_df)
21432143

2144+
@pytest.mark.parametrize("test_series", [True, False])
21442145
@pytest.mark.parametrize("periods,fill_method,limit", [
21452146
(1, 'ffill', None), (1, 'ffill', 1),
21462147
(1, 'bfill', None), (1, 'bfill', 1),
21472148
(-1, 'ffill', None), (-1, 'ffill', 1),
21482149
(-1, 'bfill', None), (-1, 'bfill', 1)])
2149-
def test_pct_change(self, periods, fill_method, limit):
2150+
def test_pct_change(self, test_series, periods, fill_method, limit):
21502151
vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan]
21512152
exp_vals = Series(vals).pct_change(periods=periods,
21522153
fill_method=fill_method,
21532154
limit=limit).tolist()
21542155

21552156
df = DataFrame({'key': ['a'] * len(vals) + ['b'] * len(vals),
21562157
'vals': vals * 2})
2157-
exp = DataFrame({'vals': exp_vals * 2})
2158-
result = df.groupby('key').pct_change(periods=periods,
2159-
fill_method=fill_method,
2160-
limit=limit)
2161-
2162-
tm.assert_frame_equal(result, exp)
2158+
grp = df.groupby('key')
2159+
def get_result(grp_obj):
2160+
return grp_obj.pct_change(periods=periods,
2161+
fill_method=fill_method,
2162+
limit=limit)
2163+
2164+
if test_series:
2165+
exp = pd.Series(exp_vals * 2)
2166+
exp.name = 'vals'
2167+
grp = grp['vals']
2168+
result = get_result(grp)
2169+
tm.assert_series_equal(result, exp)
2170+
else:
2171+
exp = DataFrame({'vals': exp_vals * 2})
2172+
result = get_result(grp)
2173+
tm.assert_frame_equal(result, exp)
21632174

21642175
def test_dont_clobber_name_column(self):
21652176
df = DataFrame({'key': ['a', 'a', 'a', 'b', 'b', 'b'],

0 commit comments

Comments
 (0)