Skip to content

Commit 9e7832e

Browse files
author
Chang She
committed
ENH: first and nth for groupby. GH #994
1 parent e1bf218 commit 9e7832e

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

pandas/core/groupby.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,8 +350,19 @@ def ohlc(self):
350350
return self._cython_agg_general('ohlc')
351351

352352
def last(self):
353+
return self.nth(-1)
354+
355+
def first(self):
356+
return self.nth(0)
357+
358+
def nth(self, n):
353359
def picker(arr):
354-
return arr[-1] if arr is not None and len(arr) else np.nan
360+
if arr is not None:
361+
n_ok_pos = n >= 0 and len(arr) > n
362+
n_ok_neg = n < 0 and len(arr) >= n
363+
if n_ok_pos or n_ok_neg:
364+
return arr.iget(n)
365+
return np.nan
355366
return self.agg(picker)
356367

357368
def _cython_agg_general(self, how):

pandas/tests/test_groupby.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,25 @@ def test_basic(self):
120120
# corner cases
121121
self.assertRaises(Exception, grouped.aggregate, lambda x: x * 2)
122122

123+
grouped = self.df.groupby('A')
124+
first = grouped.first()
125+
expected = grouped.get_group('bar')
126+
expected = expected.xs(expected.index[0])[1:]
127+
expected.name ='bar'
128+
assert_series_equal(first.xs('bar'), expected)
129+
130+
last = grouped.last()
131+
expected = grouped.get_group('bar')
132+
expected = expected.xs(expected.index[-1])[1:]
133+
expected.name ='bar'
134+
assert_series_equal(last.xs('bar'), expected)
135+
136+
nth = grouped.nth(1)
137+
expected = grouped.get_group('foo')
138+
expected = expected.xs(expected.index[1])[1:]
139+
expected.name ='foo'
140+
assert_series_equal(nth.xs('foo'), expected)
141+
123142
def test_groupby_dict_mapping(self):
124143
# GH #679
125144
from pandas import Series

0 commit comments

Comments
 (0)