|
3 | 3 | import numpy as np
|
4 | 4 | import pandas as pd
|
5 | 5 | from pandas.util import testing as tm
|
6 |
| -from pandas import Series, DataFrame, Timestamp, MultiIndex, concat |
| 6 | +from pandas import Series, DataFrame, Timestamp, MultiIndex, concat, date_range |
7 | 7 | from pandas.types.common import _ensure_platform_int
|
8 | 8 | from .common import MixIn, assert_fp_equal
|
9 | 9 |
|
@@ -190,6 +190,43 @@ def test_transform_bug(self):
|
190 | 190 | expected = Series(np.arange(5, 0, step=-1), name='B')
|
191 | 191 | assert_series_equal(result, expected)
|
192 | 192 |
|
| 193 | + def test_transform_datetime_to_timedelta(self): |
| 194 | + # GH 15429 |
| 195 | + # transforming a datetime to timedelta |
| 196 | + df = DataFrame(dict(A=Timestamp('20130101'), B=np.arange(5))) |
| 197 | + expected = pd.Series([ |
| 198 | + Timestamp('20130101') - Timestamp('20130101')] * 5, name='A') |
| 199 | + |
| 200 | + # this does date math without changing result type in transform |
| 201 | + base_time = df['A'][0] |
| 202 | + result = df.groupby('A')['A'].transform( |
| 203 | + lambda x: x.max() - x.min() + base_time) - base_time |
| 204 | + assert_series_equal(result, expected) |
| 205 | + |
| 206 | + # this does date math and causes the transform to return timedelta |
| 207 | + result = df.groupby('A')['A'].transform(lambda x: x.max() - x.min()) |
| 208 | + assert_series_equal(result, expected) |
| 209 | + |
| 210 | + def test_transform_datetime_to_numeric(self): |
| 211 | + # GH 10972 |
| 212 | + # convert dt to float |
| 213 | + df = DataFrame({ |
| 214 | + 'a': 1, 'b': date_range('2015-01-01', periods=2, freq='D')}) |
| 215 | + result = df.groupby('a').b.transform( |
| 216 | + lambda x: x.dt.dayofweek - x.dt.dayofweek.mean()) |
| 217 | + |
| 218 | + expected = Series([-0.5, 0.5], name='b') |
| 219 | + assert_series_equal(result, expected) |
| 220 | + |
| 221 | + # convert dt to int |
| 222 | + df = DataFrame({ |
| 223 | + 'a': 1, 'b': date_range('2015-01-01', periods=2, freq='D')}) |
| 224 | + result = df.groupby('a').b.transform( |
| 225 | + lambda x: x.dt.dayofweek - x.dt.dayofweek.min()) |
| 226 | + |
| 227 | + expected = Series([0, 1], name='b') |
| 228 | + assert_series_equal(result, expected) |
| 229 | + |
193 | 230 | def test_transform_multiple(self):
|
194 | 231 | grouped = self.ts.groupby([lambda x: x.year, lambda x: x.month])
|
195 | 232 |
|
|
0 commit comments