Skip to content

BUG: GH15426 timezone lost in groupby-agg with cython functions #15433

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
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 @@ -622,6 +622,7 @@ Bug Fixes

- Bug in ``DataFrame.to_stata()`` and ``StataWriter`` which produces incorrectly formatted files to be produced for some locales (:issue:`13856`)
- Bug in ``pd.concat()`` in which concatting with an empty dataframe with ``join='inner'`` was being improperly handled (:issue:`15328`)
- Bug in ``groupby.agg()`` incorrectly localizing timezone on ``datetime`` (:issue:`15426`, :issue:`10668`)



Expand Down
31 changes: 30 additions & 1 deletion pandas/tests/groupby/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""

from __future__ import print_function
from datetime import datetime
from datetime import datetime, timedelta
from functools import partial

import numpy as np
Expand Down Expand Up @@ -738,3 +738,32 @@ def test_agg_over_numpy_arrays(self):
columns=expected_column)

assert_frame_equal(result, expected)

def test_agg_time_zone_round_trip(self):
# GH 15426
ts = pd.Timestamp("2016-01-01 12:00:00", tz='US/Pacific')
df = pd.DataFrame({'a': 1, 'b': [ts + timedelta(minutes=nn)
for nn in range(10)]})

result1 = df.groupby('a')['b'].agg(np.min).iloc[0]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compare with .min() as well

result2 = df.groupby('a')['b'].agg(lambda x: np.min(x)).iloc[0]
result3 = df.groupby('a')['b'].min().iloc[0]

self.assertEqual(result1, ts)
self.assertEqual(result2, ts)
self.assertEqual(result3, ts)

dates = [pd.Timestamp("2016-01-0%d 12:00:00" % i, tz='US/Pacific')
for i in range(1, 5)]
df = pd.DataFrame({'A': ['a', 'b'] * 2, 'B': dates})
grouped = df.groupby('A')

ts = df['B'].iloc[0]
self.assertEqual(ts, grouped.nth(0)['B'].iloc[0])
self.assertEqual(ts, grouped.head(1)['B'].iloc[0])
self.assertEqual(ts, grouped.first()['B'].iloc[0])
self.assertEqual(ts, grouped.apply(lambda x: x.iloc[0])[0])

ts = df['B'].iloc[2]
self.assertEqual(ts, grouped.last()['B'].iloc[0])
self.assertEqual(ts, grouped.apply(lambda x: x.iloc[-1])[0])
9 changes: 8 additions & 1 deletion pandas/tests/types/test_cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from datetime import datetime
import numpy as np

from pandas import Timedelta, Timestamp
from pandas import Timedelta, Timestamp, DatetimeIndex
from pandas.types.cast import (_possibly_downcast_to_dtype,
_possibly_convert_objects,
_infer_dtype_from_scalar,
Expand Down Expand Up @@ -71,6 +71,13 @@ def test_datetimelikes_nan(self):
res = _possibly_downcast_to_dtype(arr, 'timedelta64[ns]')
tm.assert_numpy_array_equal(res, exp)

def test_datetime_downcast(self):
# GH 15426
ts = Timestamp("2016-01-01 12:00:00", tz='US/Pacific')
exp = DatetimeIndex([ts, ts])
res = _possibly_downcast_to_dtype(exp.asi8, exp.dtype)
tm.assert_index_equal(res, exp)


class TestInferDtype(tm.TestCase):

Expand Down
3 changes: 2 additions & 1 deletion pandas/types/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ def trans(x): # noqa
if dtype.tz:
# convert to datetime and change timezone
from pandas import to_datetime
result = to_datetime(result).tz_localize(dtype.tz)
result = to_datetime(result).tz_localize('utc')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can add addtl tests in pandas/tests/types/test_cast.py fit them in as appropriate. take out this fix temporarily to validate your test cases, then add back to make sure they work.

result = result.tz_convert(dtype.tz)

except:
pass
Expand Down