Skip to content

Commit 2fde249

Browse files
committed
BUG: Fix pandas-dev#9903
Fixes a bug where calling shift on an empty DatetimeIndex would result in the returned value being an Index rather than a DatetimeIndex.
1 parent d0f5ff4 commit 2fde249

File tree

4 files changed

+26
-5
lines changed

4 files changed

+26
-5
lines changed

pandas/core/index.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1163,7 +1163,12 @@ def shift(self, periods=1, freq=None):
11631163
return self
11641164

11651165
offset = periods * freq
1166-
return Index([idx + offset for idx in self], name=self.name)
1166+
# If this is called from a subclass override, it shouldn't change the
1167+
# type.
1168+
return type(self)(
1169+
[idx + offset for idx in self],
1170+
**self._get_attributes_dict()
1171+
)
11671172

11681173
def argsort(self, *args, **kwargs):
11691174
"""

pandas/tseries/index.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,6 @@ def __new__(cls, data=None,
203203

204204
dayfirst = kwargs.pop('dayfirst', None)
205205
yearfirst = kwargs.pop('yearfirst', None)
206-
207206
freq_infer = False
208207
if not isinstance(freq, DateOffset):
209208

@@ -254,7 +253,10 @@ def __new__(cls, data=None,
254253
data.name = name
255254

256255
if tz is not None:
257-
return data.tz_localize(tz, ambiguous=ambiguous)
256+
if data.tz is None:
257+
return data.tz_localize(tz, ambiguous=ambiguous)
258+
else:
259+
return data.tz_convert(tz)
258260

259261
return data
260262

pandas/tseries/tests/test_base.py

+6
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,12 @@ def test_nonunique_contains(self):
302302
['2015', '2015', '2016'], ['2015', '2015', '2014'])):
303303
tm.assertIn(idx[0], idx)
304304

305+
def test_shift_empty_index(self):
306+
# GH 9903
307+
idx = DatetimeIndex([], tz='UTC')
308+
shifted = idx.shift(1, freq='10T')
309+
tm.assert_index_equal(idx, shifted)
310+
305311

306312
class TestTimedeltaIndexOps(Ops):
307313

pandas/tseries/tests/test_timezones.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -701,8 +701,16 @@ def test_shift_localized(self):
701701
dr = date_range('2011/1/1', '2012/1/1', freq='W-FRI')
702702
dr_tz = dr.tz_localize(self.tzstr('US/Eastern'))
703703

704-
result = dr_tz.shift(1, '10T')
705-
self.assertEqual(result.tz, dr_tz.tz)
704+
for range_ in (dr, dr_tz):
705+
result = range_.shift(1, '10T')
706+
self.assertEqual(result.tz, range_.tz)
707+
708+
# Results should be 10 minutes apart whether the range is localized
709+
# or not.
710+
np.testing.assert_array_equal(
711+
(result - range_).minute,
712+
np.full((len(dr)), 10, dtype='int32'),
713+
)
706714

707715
def test_tz_aware_asfreq(self):
708716
dr = date_range(

0 commit comments

Comments
 (0)