Skip to content

BUG: groupby's first/last functions maintain Series rather than convert to numpy array (#15884) #15885

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

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,7 @@ Groupby/Resample/Rolling
- Bug in ``.rolling()`` where ``pd.Timedelta`` or ``datetime.timedelta`` was not accepted as a ``window`` argument (:issue:`15440`)
- Bug in ``Rolling.quantile`` function that caused a segmentation fault when called with a quantile value outside of the range [0, 1] (:issue:`15463`)
- Bug in ``DataFrame.resample().median()`` if duplicate column names are present (:issue:`14233`)
- Bug in ``.groupby()`` when calling ``first()`` or ``last()`` on TZ-aware timestamps (:issue:`15884`)

Sparse
^^^^^^
Expand Down
6 changes: 2 additions & 4 deletions pandas/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1162,11 +1162,10 @@ def first_compat(x, axis=0):

def first(x):

x = np.asarray(x)
x = x[notnull(x)]
if len(x) == 0:
return np.nan
return x[0]
return x.iloc[0]

if isinstance(x, DataFrame):
return x.apply(first, axis=axis)
Expand All @@ -1177,11 +1176,10 @@ def last_compat(x, axis=0):

def last(x):

x = np.asarray(x)
x = x[notnull(x)]
if len(x) == 0:
return np.nan
return x[-1]
return x.iloc[-1]

if isinstance(x, DataFrame):
return x.apply(last, axis=axis)
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ def test_select_bad_cols(self):
# will have to rethink regex if you change message!
g[['A', 'C']]

def test_first_last_timestamp(self):
# GH15884
df = pd.DataFrame({'time': [pd.Timestamp('2012-01-01 13:00:00+00:00')],
'A': [3]})
result = df.groupby('A', as_index=False).first()
assert_frame_equal(df, result)
result = df.groupby('A', as_index=False).last()
assert_frame_equal(df, result)

def test_first_last_nth(self):
# tests for first / last / nth
grouped = self.df.groupby('A')
Expand Down