Skip to content

Commit af01122

Browse files
discortTomAugspurger
authored andcommitted
Added applying of multiple columns to resample (#17950)
(cherry picked from commit bdeadb9)
1 parent c5673af commit af01122

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

doc/source/whatsnew/v0.21.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ Documentation Changes
5656

5757
Bug Fixes
5858
~~~~~~~~~
59+
- Bug in ``DataFrame.resample(...).apply(...)`` when there is a callable that returns different columns (:issue:`15169`)
5960

6061
Conversion
6162
^^^^^^^^^^

pandas/core/resample.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,11 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
395395
grouped = PanelGroupBy(obj, grouper=grouper, axis=self.axis)
396396

397397
try:
398-
result = grouped.aggregate(how, *args, **kwargs)
398+
if isinstance(obj, ABCDataFrame) and compat.callable(how):
399+
# Check if the function is reducing or not.
400+
result = grouped._aggregate_item_by_item(how, *args, **kwargs)
401+
else:
402+
result = grouped.aggregate(how, *args, **kwargs)
399403
except Exception:
400404

401405
# we have a non-reducing function

pandas/tests/test_resample.py

+20
Original file line numberDiff line numberDiff line change
@@ -3103,6 +3103,26 @@ def f(x):
31033103
result = g.apply(f)
31043104
assert_frame_equal(result, expected)
31053105

3106+
def test_apply_with_mutated_index(self):
3107+
# GH 15169
3108+
index = pd.date_range('1-1-2015', '12-31-15', freq='D')
3109+
df = pd.DataFrame(data={'col1': np.random.rand(len(index))},
3110+
index=index)
3111+
3112+
def f(x):
3113+
s = pd.Series([1, 2], index=['a', 'b'])
3114+
return s
3115+
3116+
expected = df.groupby(pd.Grouper(freq='M')).apply(f)
3117+
3118+
result = df.resample('M').apply(f)
3119+
assert_frame_equal(result, expected)
3120+
3121+
# A case for series
3122+
expected = df['col1'].groupby(pd.Grouper(freq='M')).apply(f)
3123+
result = df['col1'].resample('M').apply(f)
3124+
assert_series_equal(result, expected)
3125+
31063126
def test_resample_groupby_with_label(self):
31073127
# GH 13235
31083128
index = date_range('2000-01-01', freq='2D', periods=5)

0 commit comments

Comments
 (0)