Skip to content

Commit 387ec4d

Browse files
committed
ENH: column selection via attributes on DataFrameGroupBy, GH #882
1 parent a87432d commit 387ec4d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

pandas/core/groupby.py

+28
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,12 @@ def _obj_with_exclusions(self):
139139
return self.obj
140140

141141
def __getattr__(self, attr):
142+
if attr in self.obj:
143+
return self[attr]
144+
142145
if hasattr(self.obj, attr) and attr != '_cache':
143146
return self._make_wrapper(attr)
147+
144148
raise AttributeError("'%s' object has no attribute '%s'" %
145149
(type(self).__name__, attr))
146150

@@ -1644,3 +1648,27 @@ def numpy_groupby(data, labels, axis=0):
16441648
group_sums = np.add.reduceat(ordered_data, groups_at, axis=axis)
16451649

16461650
return group_sums
1651+
1652+
from pandas.util import py3compat
1653+
import sys
1654+
1655+
def install_ipython_completers(): # pragma: no cover
1656+
"""Register the DataFrame type with IPython's tab completion machinery, so
1657+
that it knows about accessing column names as attributes."""
1658+
from IPython.utils.generics import complete_object
1659+
1660+
@complete_object.when_type(DataFrameGroupBy)
1661+
def complete_dataframe(obj, prev_completions):
1662+
return prev_completions + [c for c in obj.obj.columns \
1663+
if isinstance(c, basestring) and py3compat.isidentifier(c)]
1664+
1665+
1666+
# Importing IPython brings in about 200 modules, so we want to avoid it unless
1667+
# we're in IPython (when those modules are loaded anyway).
1668+
if "IPython" in sys.modules: # pragma: no cover
1669+
try:
1670+
install_ipython_completers()
1671+
except Exception:
1672+
pass
1673+
1674+

pandas/tests/test_groupby.py

+10
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,16 @@ def test_intercept_builtin_sum(self):
15421542
assert_series_equal(result, expected)
15431543
assert_series_equal(result2, expected)
15441544

1545+
def test_column_select_via_attr(self):
1546+
result = self.df.groupby('A').C.sum()
1547+
expected = self.df.groupby('A')['C'].sum()
1548+
assert_series_equal(result, expected)
1549+
1550+
self.df['mean'] = 1.5
1551+
result = self.df.groupby('A').mean()
1552+
expected = self.df.groupby('A').agg(np.mean)
1553+
assert_frame_equal(result, expected)
1554+
15451555
def _check_groupby(df, result, keys, field, f=lambda x: x.sum()):
15461556
tups = map(tuple, df[keys].values)
15471557
tups = com._asarray_tuplesafe(tups)

0 commit comments

Comments
 (0)