Skip to content

Commit 10edfd0

Browse files
jbrockmendeljreback
authored andcommitted
Fix DatetimeIndex.insert(pd.NaT) for tz-aware index (#18883)
closes #16357
1 parent 7958018 commit 10edfd0

File tree

3 files changed

+11
-8
lines changed

3 files changed

+11
-8
lines changed

doc/source/whatsnew/v0.23.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ Indexing
313313
- :func:`Index.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`)
314314
- :func:`DatetimeIndex.to_series` now accepts ``index`` and ``name`` kwargs (:issue:`18699`)
315315
- Bug in indexing non-scalar value from ``Series`` having non-unique ``Index`` will return value flattened (:issue:`17610`)
316+
- Bug in :func:`DatetimeIndex.insert` where inserting ``NaT`` into a timezone-aware index incorrectly raised (:issue:`16357`)
316317

317318

318319
I/O

pandas/core/indexes/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1791,7 +1791,7 @@ def insert(self, loc, item):
17911791

17921792
if isinstance(item, (datetime, np.datetime64)):
17931793
self._assert_can_do_op(item)
1794-
if not self._has_same_tz(item):
1794+
if not self._has_same_tz(item) and not isna(item):
17951795
raise ValueError(
17961796
'Passed item and index have different timezone')
17971797
# check freq can be preserved on edge cases

pandas/tests/indexes/datetimes/test_indexing.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,15 @@ def test_where_tz(self):
4646
expected = i2
4747
tm.assert_index_equal(result, expected)
4848

49+
@pytest.mark.parametrize('null', [None, np.nan, pd.NaT])
50+
@pytest.mark.parametrize('tz', [None, 'UTC', 'US/Eastern'])
51+
def test_insert_nat(self, tz, null):
52+
# GH#16537, GH#18295 (test missing)
53+
idx = pd.DatetimeIndex(['2017-01-01'], tz=tz)
54+
expected = pd.DatetimeIndex(['NaT', '2017-01-01'], tz=tz)
55+
res = idx.insert(0, null)
56+
tm.assert_index_equal(res, expected)
57+
4958
def test_insert(self):
5059
idx = DatetimeIndex(
5160
['2000-01-04', '2000-01-01', '2000-01-02'], name='idx')
@@ -145,13 +154,6 @@ def test_insert(self):
145154
assert result.tz == expected.tz
146155
assert result.freq is None
147156

148-
# GH 18295 (test missing)
149-
expected = DatetimeIndex(
150-
['20170101', pd.NaT, '20170102', '20170103', '20170104'])
151-
for na in (np.nan, pd.NaT, None):
152-
result = date_range('20170101', periods=4).insert(1, na)
153-
tm.assert_index_equal(result, expected)
154-
155157
def test_delete(self):
156158
idx = date_range(start='2000-01-01', periods=5, freq='M', name='idx')
157159

0 commit comments

Comments
 (0)