Skip to content

Commit a09b3d5

Browse files
meeseeksmachinejreback
authored andcommitted
Backport PR #27556: BUG: Allow ensure_index to coerce nan to NaT with numpy object array and tz Timestamp (#27561)
1 parent 02d1fb0 commit a09b3d5

File tree

4 files changed

+16
-15
lines changed

4 files changed

+16
-15
lines changed

doc/source/whatsnew/v0.25.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ Timedelta
5050
Timezones
5151
^^^^^^^^^
5252

53-
-
53+
- Bug in :class:`Index` where a numpy object array with a timezone aware :class:`Timestamp` and ``np.nan`` would not return a :class:`DatetimeIndex` (:issue:`27011`)
5454
-
5555
-
5656

pandas/core/indexes/base.py

+8-12
Original file line numberDiff line numberDiff line change
@@ -489,19 +489,15 @@ def __new__(
489489
pass
490490
elif inferred != "string":
491491
if inferred.startswith("datetime"):
492-
if (
493-
lib.is_datetime_with_singletz_array(subarr)
494-
or "tz" in kwargs
495-
):
496-
# only when subarr has the same tz
497-
from pandas import DatetimeIndex
492+
from pandas import DatetimeIndex
498493

499-
try:
500-
return DatetimeIndex(
501-
subarr, copy=copy, name=name, **kwargs
502-
)
503-
except OutOfBoundsDatetime:
504-
pass
494+
try:
495+
return DatetimeIndex(subarr, copy=copy, name=name, **kwargs)
496+
except (ValueError, OutOfBoundsDatetime):
497+
# GH 27011
498+
# If we have mixed timezones, just send it
499+
# down the base constructor
500+
pass
505501

506502
elif inferred.startswith("timedelta"):
507503
from pandas import TimedeltaIndex

pandas/tests/arrays/interval/test_interval.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,9 @@ class TestAttributes:
4242
(0, 1),
4343
(Timedelta("0 days"), Timedelta("1 day")),
4444
(Timestamp("2018-01-01"), Timestamp("2018-01-02")),
45-
pytest.param(
45+
(
4646
Timestamp("2018-01-01", tz="US/Eastern"),
4747
Timestamp("2018-01-02", tz="US/Eastern"),
48-
marks=pytest.mark.xfail(strict=True, reason="GH 27011"),
4948
),
5049
],
5150
)

pandas/tests/indexes/datetimes/test_construction.py

+6
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,12 @@ def test_constructor_wrong_precision_raises(self):
822822
with pytest.raises(ValueError):
823823
pd.DatetimeIndex(["2000"], dtype="datetime64[us]")
824824

825+
def test_index_constructor_with_numpy_object_array_and_timestamp_tz_with_nan(self):
826+
# GH 27011
827+
result = Index(np.array([Timestamp("2019", tz="UTC"), np.nan], dtype=object))
828+
expected = DatetimeIndex([Timestamp("2019", tz="UTC"), pd.NaT])
829+
tm.assert_index_equal(result, expected)
830+
825831

826832
class TestTimeSeries:
827833
def test_dti_constructor_preserve_dti_freq(self):

0 commit comments

Comments
 (0)