Skip to content

Commit 794cbc8

Browse files
committed
Resampler.__iter__ is returned iterable obj
1 parent 1ea9664 commit 794cbc8

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed

doc/source/timeseries.rst

+17
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,23 @@ regularity will result in a ``DatetimeIndex``, although frequency is lost:
703703
704704
ts2[[0, 2, 6]].index
705705
706+
.. _timeseries.iterating:
707+
708+
Iterating through groups
709+
------------------------
710+
711+
With the Resampler object in hand, iterating through the grouped data is very
712+
natural and functions similarly to :py:func:`itertools.groupby`:
713+
714+
.. ipython::
715+
716+
In [1]: resampled = df.resample('H')
717+
718+
In [2]: for name, group in resampled:
719+
...: print(name)
720+
...: print(group)
721+
...:
722+
706723
.. _timeseries.components:
707724

708725
Time/Date Components

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ Other Enhancements
182182
- :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`)
183183
- :class:`Series` and :class:`DataFrame` now support :class:`Iterable` in constructor (:issue:`2193`)
184184
- :class:`DatetimeIndex` gained :attr:`DatetimeIndex.timetz` attribute. Returns local time with timezone information. (:issue:`21358`)
185+
- :class:`Resampler` now is iterable like :class:`GroupBy` (:issue:`15314`).
185186

186187
.. _whatsnew_0240.api_breaking:
187188

pandas/core/resample.py

+17
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,23 @@ def __getattr__(self, attr):
9797

9898
return object.__getattribute__(self, attr)
9999

100+
def __iter__(self):
101+
"""
102+
Resampler iterator
103+
104+
Returns
105+
-------
106+
Generator yielding sequence of (name, subsetted object)
107+
for each group
108+
109+
See Also
110+
--------
111+
GroupBy.__iter__
112+
113+
"""
114+
self._set_binner()
115+
return super(Resampler, self).__iter__()
116+
100117
@property
101118
def obj(self):
102119
return self.groupby.obj

pandas/tests/test_resample.py

+11
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,17 @@ def test_apply_to_empty_series(self):
771771

772772
assert_series_equal(result, expected, check_dtype=False)
773773

774+
def test_resampler_is_iterable(self):
775+
# GH 15314
776+
series = self.create_series()
777+
freq = 'H'
778+
tg = TimeGrouper(freq, convention='start')
779+
grouped = series.groupby(tg)
780+
resampled = series.resample(freq)
781+
for (rk, rv), (gk, gv) in zip(resampled, grouped):
782+
assert rk == gk
783+
assert_series_equal(rv, gv)
784+
774785

775786
class TestDatetimeIndex(Base):
776787
_index_factory = lambda x: date_range

0 commit comments

Comments
 (0)