Skip to content

Commit a4f0092

Browse files
mroeschkequintusdias
authored andcommitted
BUG: Allow ensure_index to coerce nan to NaT with numpy object array and tz Timestamp (pandas-dev#27556)
1 parent 3692f88 commit a4f0092

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
@@ -469,19 +469,15 @@ def __new__(
469469
pass
470470
elif inferred != "string":
471471
if inferred.startswith("datetime"):
472-
if (
473-
lib.is_datetime_with_singletz_array(subarr)
474-
or "tz" in kwargs
475-
):
476-
# only when subarr has the same tz
477-
from pandas import DatetimeIndex
472+
from pandas import DatetimeIndex
478473

479-
try:
480-
return DatetimeIndex(
481-
subarr, copy=copy, name=name, **kwargs
482-
)
483-
except OutOfBoundsDatetime:
484-
pass
474+
try:
475+
return DatetimeIndex(subarr, copy=copy, name=name, **kwargs)
476+
except (ValueError, OutOfBoundsDatetime):
477+
# GH 27011
478+
# If we have mixed timezones, just send it
479+
# down the base constructor
480+
pass
485481

486482
elif inferred.startswith("timedelta"):
487483
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)