Skip to content

Commit f4d13fb

Browse files
committed
REF: push groupby iterator code into Grouper class
1 parent f3c0a08 commit f4d13fb

File tree

1 file changed

+35
-26
lines changed

1 file changed

+35
-26
lines changed

pandas/core/groupby.py

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -190,32 +190,7 @@ def __iter__(self):
190190
Generator yielding sequence of (name, subsetted object)
191191
for each group
192192
"""
193-
if len(self.grouper.groupings) == 1:
194-
groups = self.indices.keys()
195-
try:
196-
groups = sorted(groups)
197-
except Exception: # pragma: no cover
198-
pass
199-
200-
for name in groups:
201-
yield name, self.get_group(name)
202-
else:
203-
# provide "flattened" iterator for multi-group setting
204-
for it in self._multi_iter():
205-
yield it
206-
207-
def _multi_iter(self):
208-
data = self.obj
209-
210-
comp_ids, _, ngroups = self.grouper.group_info
211-
label_list = self.grouper.labels
212-
level_list = self.grouper.levels
213-
mapper = _KeyMapper(comp_ids, ngroups, label_list, level_list)
214-
215-
for label, group in _generate_groups(data, comp_ids, ngroups,
216-
axis=self.axis):
217-
key = mapper.get_key(label)
218-
yield key, group
193+
return self.grouper.get_iterator(self.obj, axis=self.axis)
219194

220195
def apply(self, func, *args, **kwargs):
221196
"""
@@ -449,6 +424,40 @@ def shape(self):
449424
def __iter__(self):
450425
return iter(self.indices)
451426

427+
def get_iterator(self, data, axis=0):
428+
"""
429+
Groupby iterator
430+
431+
Returns
432+
-------
433+
Generator yielding sequence of (name, subsetted object)
434+
for each group
435+
"""
436+
if len(self.groupings) == 1:
437+
indices = self.indices
438+
groups = indices.keys()
439+
try:
440+
groups = sorted(groups)
441+
except Exception: # pragma: no cover
442+
pass
443+
444+
for name in groups:
445+
inds = indices[name]
446+
group = data.take(inds, axis=axis)
447+
448+
yield name, group
449+
else:
450+
# provide "flattened" iterator for multi-group setting
451+
comp_ids, _, ngroups = self.group_info
452+
label_list = self.labels
453+
level_list = self.levels
454+
mapper = _KeyMapper(comp_ids, ngroups, label_list, level_list)
455+
456+
for label, group in _generate_groups(data, comp_ids, ngroups,
457+
axis=axis):
458+
key = mapper.get_key(label)
459+
yield key, group
460+
452461
@cache_readonly
453462
def indices(self):
454463
if len(self.groupings) == 1:

0 commit comments

Comments
 (0)