Skip to content

BUG: doc example in groupby.rst (GH7559 / GH7628) #7631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,19 +829,29 @@ def nth(self, n, dropna=None):
dropped = self.obj.dropna(how=dropna, axis=self.axis)

# get a new grouper for our dropped obj
grouper, exclusions, obj = _get_grouper(dropped, key=self.keys, axis=self.axis,
level=self.level, sort=self.sort)
if self.keys is None and self.level is None:

sizes = obj.groupby(grouper).size()
result = obj.groupby(grouper).nth(n)
# we don't have the grouper info available (e.g. we have selected out
# a column that is not in the current object)
axis = self.grouper.axis
grouper = axis[axis.isin(dropped.index)]
keys = self.grouper.names
else:

# create a grouper with the original parameters, but on the dropped object
grouper, _, _ = _get_grouper(dropped, key=self.keys, axis=self.axis,
level=self.level, sort=self.sort)

sizes = dropped.groupby(grouper).size()
result = dropped.groupby(grouper).nth(n)
mask = (sizes<max_len).values

# set the results which don't meet the criteria
if len(result) and mask.any():
result.loc[mask] = np.nan

# reset/reindex to the original groups
if len(self.obj) == len(dropped):
if len(self.obj) == len(dropped) or len(result) == len(self.grouper.result_index):
result.index = self.grouper.result_index
else:
result = result.reindex(self.grouper.result_index)
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,13 @@ def test_nth(self):
result = s.groupby(g).nth(0,dropna='all')
assert_series_equal(result,expected)

# doc example
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
result = g.B.nth(0, dropna=True)
expected = g.B.first()
assert_series_equal(result,expected)

def test_grouper_index_types(self):
# related GH5375
# groupby misbehaving when using a Floatlike index
Expand Down