Skip to content

Commit 41e3b29

Browse files
mroeschkeTomAugspurger
authored andcommitted
BUG: Retain tz transformation in groupby.transform (#27510)
* BUG: Retain tz transformation in groupby.transform
1 parent 86049dd commit 41e3b29

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

doc/source/whatsnew/v0.25.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ Plotting
120120
Groupby/resample/rolling
121121
^^^^^^^^^^^^^^^^^^^^^^^^
122122

123-
-
123+
- Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`)
124124
-
125125
-
126126

pandas/core/groupby/generic.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
from pandas.core.base import DataError, SpecificationError
4343
import pandas.core.common as com
4444
from pandas.core.frame import DataFrame
45-
from pandas.core.generic import NDFrame, _shared_docs
45+
from pandas.core.generic import ABCDataFrame, ABCSeries, NDFrame, _shared_docs
4646
from pandas.core.groupby import base
4747
from pandas.core.groupby.groupby import GroupBy, _apply_docs, _transform_template
4848
from pandas.core.index import Index, MultiIndex
@@ -1025,8 +1025,8 @@ def transform(self, func, *args, **kwargs):
10251025
object.__setattr__(group, "name", name)
10261026
res = wrapper(group)
10271027

1028-
if hasattr(res, "values"):
1029-
res = res.values
1028+
if isinstance(res, (ABCDataFrame, ABCSeries)):
1029+
res = res._values
10301030

10311031
indexer = self._get_index(name)
10321032
s = klass(res, indexer)

pandas/tests/groupby/test_transform.py

+24
Original file line numberDiff line numberDiff line change
@@ -1001,3 +1001,27 @@ def test_ffill_not_in_axis(func, key, val):
10011001
expected = df
10021002

10031003
assert_frame_equal(result, expected)
1004+
1005+
1006+
def test_transform_lambda_with_datetimetz():
1007+
# GH 27496
1008+
df = DataFrame(
1009+
{
1010+
"time": [
1011+
Timestamp("2010-07-15 03:14:45"),
1012+
Timestamp("2010-11-19 18:47:06"),
1013+
],
1014+
"timezone": ["Etc/GMT+4", "US/Eastern"],
1015+
}
1016+
)
1017+
result = df.groupby(["timezone"])["time"].transform(
1018+
lambda x: x.dt.tz_localize(x.name)
1019+
)
1020+
expected = Series(
1021+
[
1022+
Timestamp("2010-07-15 03:14:45", tz="Etc/GMT+4"),
1023+
Timestamp("2010-11-19 18:47:06", tz="US/Eastern"),
1024+
],
1025+
name="time",
1026+
)
1027+
assert_series_equal(result, expected)

0 commit comments

Comments
 (0)