Skip to content

Commit 3add483

Browse files
author
tp
committed
Added repr string for Grouper and TimeGrouper
1 parent c176a3c commit 3add483

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

doc/source/whatsnew/v0.21.1.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Other Enhancements
2222
^^^^^^^^^^^^^^^^^^
2323

2424
- :meth:`Timestamp.timestamp` is now available in Python 2.7. (:issue:`17329`)
25-
-
25+
- :class:`Grouper` and :class:`TimeGrouper` now have a friendly repr output.
2626
-
2727

2828
.. _whatsnew_0211.deprecations:

pandas/core/groupby.py

+9
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ class Grouper(object):
233233
234234
>>> df.groupby(Grouper(level='date', freq='60s', axis=1))
235235
"""
236+
_attributes = ('key', 'level', 'freq', 'axis', 'sort')
236237

237238
def __new__(cls, *args, **kwargs):
238239
if kwargs.get('freq') is not None:
@@ -333,6 +334,14 @@ def _set_grouper(self, obj, sort=False):
333334
def groups(self):
334335
return self.grouper.groups
335336

337+
def __repr__(self):
338+
attrs_list = ["{}={!r}".format(attr_name, getattr(self, attr_name))
339+
for attr_name in self._attributes
340+
if getattr(self, attr_name) is not None]
341+
attrs = ", ".join(attrs_list)
342+
cls_name = self.__class__.__name__
343+
return "{}({})".format(cls_name, attrs)
344+
336345

337346
class GroupByPlot(PandasObject):
338347
"""

pandas/core/resample.py

+3
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,9 @@ class TimeGrouper(Grouper):
10251025
Use begin, end, nperiods to generate intervals that cannot be derived
10261026
directly from the associated object
10271027
"""
1028+
_attributes = ('key', 'level', 'freq', 'sort', 'closed', 'label',
1029+
'how', 'nperiods', 'axis', 'fill_method', 'limit',
1030+
'loffset', 'kind', 'convention', 'base')
10281031

10291032
def __init__(self, freq='Min', closed=None, label=None, how='mean',
10301033
nperiods=None, axis=0,

pandas/tests/test_resample.py

+6
Original file line numberDiff line numberDiff line change
@@ -3400,3 +3400,9 @@ def test_aggregate_with_nat(self):
34003400

34013401
# if NaT is included, 'var', 'std', 'mean', 'first','last'
34023402
# and 'nth' doesn't work yet
3403+
3404+
def test_repr(self):
3405+
result = repr(TimeGrouper(key='A', freq='H'))
3406+
expected = ("TimeGrouper(key='A', freq=<Hour>, sort=True, closed='left', "
3407+
"label='left', how='mean', axis=0, convention='e', base=0)")
3408+
assert result == expected

0 commit comments

Comments
 (0)