Skip to content

Commit a046596

Browse files
authored
BUG: DatetimeIndex.insert on empty can preserve freq (#33573)
1 parent fee7d1e commit a046596

File tree

5 files changed

+32
-3
lines changed

5 files changed

+32
-3
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,7 @@ Indexing
524524
- Bug in :meth:`DataFrame.copy` _item_cache not invalidated after copy causes post-copy value updates to not be reflected (:issue:`31784`)
525525
- Bug in `Series.__getitem__` with an integer key and a :class:`MultiIndex` with leading integer level failing to raise ``KeyError`` if the key is not present in the first level (:issue:`33355`)
526526
- Bug in :meth:`DataFrame.iloc` when slicing a single column-:class:`DataFrame`` with ``ExtensionDtype`` (e.g. ``df.iloc[:, :1]``) returning an invalid result (:issue:`32957`)
527+
- Bug in :meth:`DatetimeIndex.insert` and :meth:`TimedeltaIndex.insert` causing index ``freq`` to be lost when setting an element into an empty :class:`Series` (:issue:33573`)
527528

528529
Missing
529530
^^^^^^^

pandas/core/indexes/datetimelike.py

+4
Original file line numberDiff line numberDiff line change
@@ -941,6 +941,10 @@ def insert(self, loc, item):
941941
freq = self.freq
942942
elif (loc == len(self)) and item - self.freq == self[-1]:
943943
freq = self.freq
944+
elif self.freq is not None:
945+
# Adding a single item to an empty index may preserve freq
946+
if self.freq.is_on_offset(item):
947+
freq = self.freq
944948
item = item.asm8
945949

946950
try:

pandas/tests/indexes/datetimes/test_insert.py

+14
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,20 @@ def test_insert_invalid_na(self, tz):
2424
with pytest.raises(TypeError, match="incompatible label"):
2525
idx.insert(0, np.timedelta64("NaT"))
2626

27+
def test_insert_empty_preserves_freq(self, tz_naive_fixture):
28+
# GH#33573
29+
tz = tz_naive_fixture
30+
dti = DatetimeIndex([], tz=tz, freq="D")
31+
item = Timestamp("2017-04-05").tz_localize(tz)
32+
33+
result = dti.insert(0, item)
34+
assert result.freq == dti.freq
35+
36+
# But not when we insert an item that doesnt conform to freq
37+
dti = DatetimeIndex([], tz=tz, freq="W-THU")
38+
result = dti.insert(0, item)
39+
assert result.freq is None
40+
2741
def test_insert(self):
2842
idx = DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"], name="idx")
2943

pandas/tests/indexes/timedeltas/test_insert.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,15 @@ def test_insert_dont_cast_strings(self):
9393

9494
def test_insert_empty(self):
9595
# Corner case inserting with length zero doesnt raise IndexError
96+
# GH#33573 for freq preservation
9697
idx = timedelta_range("1 Day", periods=3)
9798
td = idx[0]
9899

99-
idx[:0].insert(0, td)
100-
idx[:0].insert(1, td)
101-
idx[:0].insert(-1, td)
100+
result = idx[:0].insert(0, td)
101+
assert result.freq == "D"
102+
103+
result = idx[:0].insert(1, td)
104+
assert result.freq == "D"
105+
106+
result = idx[:0].insert(-1, td)
107+
assert result.freq == "D"

pandas/tests/series/indexing/test_indexing.py

+4
Original file line numberDiff line numberDiff line change
@@ -284,17 +284,21 @@ def test_setitem(datetime_series, string_series):
284284
expected = string_series.append(app)
285285
tm.assert_series_equal(s, expected)
286286

287+
288+
def test_setitem_empty_series():
287289
# Test for issue #10193
288290
key = pd.Timestamp("2012-01-01")
289291
series = pd.Series(dtype=object)
290292
series[key] = 47
291293
expected = pd.Series(47, [key])
292294
tm.assert_series_equal(series, expected)
293295

296+
# GH#33573 our index should retain its freq
294297
series = pd.Series([], pd.DatetimeIndex([], freq="D"), dtype=object)
295298
series[key] = 47
296299
expected = pd.Series(47, pd.DatetimeIndex([key], freq="D"))
297300
tm.assert_series_equal(series, expected)
301+
assert series.index.freq == expected.index.freq
298302

299303

300304
def test_setitem_dtypes():

0 commit comments

Comments
 (0)