Skip to content

Commit 9c8800d

Browse files
Backport PR #54880 on branch 2.1.x (REGR: comparing datetime vs None raises) (#54925)
Backport PR #54880: REGR: comparing datetime vs None raises Co-authored-by: Patrick Hoefler <[email protected]>
1 parent cbff8f1 commit 9c8800d

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v2.1.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ including other versions of pandas.
1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
1616
- Fixed regression in :meth:`DataFrame.__setitem__` raising ``AssertionError`` when setting a :class:`Series` with a partial :class:`MultiIndex` (:issue:`54875`)
17+
- Fixed regression when comparing a :class:`Series` with ``datetime64`` dtype with ``None`` (:issue:`54870`)
1718

1819
.. ---------------------------------------------------------------------------
1920
.. _whatsnew_211.bug_fixes:

pandas/core/arrays/datetimelike.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
algorithms,
108108
missing,
109109
nanops,
110+
ops,
110111
)
111112
from pandas.core.algorithms import (
112113
checked_add_with_arr,
@@ -943,8 +944,12 @@ def _cmp_method(self, other, op):
943944

944945
dtype = getattr(other, "dtype", None)
945946
if is_object_dtype(dtype):
946-
return op(np.asarray(self, dtype=object), other)
947-
947+
# We have to use comp_method_OBJECT_ARRAY instead of numpy
948+
# comparison otherwise it would raise when comparing to None
949+
result = ops.comp_method_OBJECT_ARRAY(
950+
op, np.asarray(self.astype(object)), other
951+
)
952+
return result
948953
if other is NaT:
949954
if op is operator.ne:
950955
result = np.ones(self.shape, dtype=bool)

pandas/tests/series/indexing/test_datetime.py

+9
Original file line numberDiff line numberDiff line change
@@ -486,3 +486,12 @@ def test_getitem_str_second_with_datetimeindex():
486486
msg = r"Timestamp\('2012-01-02 18:01:02-0600', tz='US/Central'\)"
487487
with pytest.raises(KeyError, match=msg):
488488
df[df.index[2]]
489+
490+
491+
def test_compare_datetime_with_all_none():
492+
# GH#54870
493+
ser = Series(["2020-01-01", "2020-01-02"], dtype="datetime64[ns]")
494+
ser2 = Series([None, None])
495+
result = ser > ser2
496+
expected = Series([False, False])
497+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)