Skip to content

Commit cf156cf

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

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

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

+12
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,18 @@ 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 not in categories should raise
192+
# for unequal comps, but not for equal/not equal
193+
cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
194+
195+
msg = ("Cannot compare a Categorical for op __{}__ with a scalar,"
196+
" which is not a category")
197+
198+
tm.assert_numpy_array_equal(cat <= 2,
199+
np.array([True, True, False, False]))
200+
189201
@pytest.mark.parametrize('data,reverse,base', [
190202
(list("abc"), list("cba"), list("bbb")),
191203
([1, 2, 3], [3, 2, 1], [2, 2, 2])]

0 commit comments

Comments
 (0)