File tree Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -350,8 +350,19 @@ def ohlc(self):
350
350
return self ._cython_agg_general ('ohlc' )
351
351
352
352
def last (self ):
353
+ return self .nth (- 1 )
354
+
355
+ def first (self ):
356
+ return self .nth (0 )
357
+
358
+ def nth (self , n ):
353
359
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
355
366
return self .agg (picker )
356
367
357
368
def _cython_agg_general (self , how ):
Original file line number Diff line number Diff line change @@ -120,6 +120,25 @@ def test_basic(self):
120
120
# corner cases
121
121
self .assertRaises (Exception , grouped .aggregate , lambda x : x * 2 )
122
122
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
+
123
142
def test_groupby_dict_mapping (self ):
124
143
# GH #679
125
144
from pandas import Series
You can’t perform that action at this time.
0 commit comments