Skip to content

Commit 261a0c2

Browse files
committed
BUG: make Series.tz_localize work with length-0 non-DatetimeIndex. close pandas-dev#2248
1 parent 3f4f285 commit 261a0c2

File tree

4 files changed

+25
-1
lines changed

4 files changed

+25
-1
lines changed

RELEASE.rst

+1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ pandas 0.9.1
110110
- Fix issue constructing DataFrame from empty Series with name (#2234)
111111
- Use console-width detection in interactive sessions only (#1610)
112112
- Fix parallel_coordinates legend bug with mpl 1.2.0 (#2237)
113+
- Make tz_localize work in corner case of empty Series (#2248)
113114
114115
pandas 0.9.0
115116
============

pandas/core/series.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -2756,7 +2756,15 @@ def tz_localize(self, tz, copy=True):
27562756
-------
27572757
localized : TimeSeries
27582758
"""
2759-
new_index = self.index.tz_localize(tz)
2759+
from pandas.tseries.index import DatetimeIndex
2760+
2761+
if not isinstance(self.index, DatetimeIndex):
2762+
if len(self.index) > 0:
2763+
raise Exception('Cannot tz-localize non-time series')
2764+
2765+
new_index = DatetimeIndex([], tz=tz)
2766+
else:
2767+
new_index = self.index.tz_localize(tz)
27602768

27612769
new_values = self.values
27622770
if copy:

pandas/tseries/index.py

+4
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,10 @@ def __new__(cls, data=None,
203203
if isinstance(data, DatetimeIndex):
204204
if name is not None:
205205
data.name = name
206+
207+
if tz is not None:
208+
return data.tz_localize(tz)
209+
206210
return data
207211

208212
if issubclass(data.dtype.type, basestring):

pandas/tseries/tests/test_timezones.py

+11
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,17 @@ def test_tz_localize_dti(self):
137137
freq='L')
138138
self.assertRaises(pytz.NonExistentTimeError, dti.tz_localize, 'US/Eastern')
139139

140+
def test_tz_localize_empty_series(self):
141+
# #2248
142+
143+
ts = Series()
144+
145+
ts2 = ts.tz_localize('utc')
146+
self.assertTrue(ts2.index.tz == pytz.utc)
147+
148+
ts2 = ts.tz_localize('US/Eastern')
149+
self.assertTrue(ts2.index.tz == pytz.timezone('US/Eastern'))
150+
140151
def test_astimezone(self):
141152
utc = Timestamp('3/11/2012 22:00', tz='UTC')
142153
expected = utc.tz_convert('US/Eastern')

0 commit comments

Comments
 (0)