Skip to content

Commit e41387d

Browse files
committed
BUG: None comparison evaluates to True pandas-dev#26504
1 parent d3a1912 commit e41387d

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ Categorical
305305
^^^^^^^^^^^
306306

307307
- Bug in :func:`DataFrame.at` and :func:`Series.at` that would raise exception if the index was a :class:`CategoricalIndex` (:issue:`20629`)
308-
-
308+
- Bug in :func:`_cat_compare_op` that would valuate comparison with None to True (:issue:`26504`)
309309
-
310310

311311
Datetimelike

pandas/core/arrays/categorical.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,15 @@ def f(self, other):
100100
if is_scalar(other):
101101
if other in self.categories:
102102
i = self.categories.get_loc(other)
103-
return getattr(self._codes, op)(i)
103+
f = getattr(self._codes, op)
104+
ret = f(i)
105+
106+
# check for NaN in self
107+
na_mask = (self._codes == -1)
108+
if na_mask.any():
109+
# In other series, the leads to False, so do that here too
110+
ret[na_mask] = False
111+
return ret
104112
else:
105113
if op == '__eq__':
106114
return np.repeat(False, len(self))

pandas/tests/arrays/categorical/test_operators.py

+13
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,19 @@ def test_comparison_with_unknown_scalars(self):
186186
tm.assert_numpy_array_equal(cat != 4,
187187
np.array([True, True, True]))
188188

189+
def test_comparison_with_known_scalars(self):
190+
# https://github.com/pandas-dev/pandas/issues/26504
191+
# and following comparisons with scalars in categories with None should
192+
# be evaluated as False
193+
194+
cat1 = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
195+
cat2 = Categorical([None, 1, 2, 3], categories=[1, 2, 3], ordered=True)
196+
197+
tm.assert_numpy_array_equal(cat1 <= 2,
198+
np.array([True, True, False, False]))
199+
tm.assert_numpy_array_equal(cat2 <= 2,
200+
np.array([False, True, True, False]))
201+
189202
@pytest.mark.parametrize('data,reverse,base', [
190203
(list("abc"), list("cba"), list("bbb")),
191204
([1, 2, 3], [3, 2, 1], [2, 2, 2])]

0 commit comments

Comments
 (0)