{"record":{"id":"75953ba57d27e82a","repo":"pandas-dev/pandas","slug":"cannot-compare-a-categorical-for-op-opname-with","errorCode":null,"errorMessage":"Cannot compare a Categorical for op {opname} with type {type(other)}.\nIf you want to compare values, use 'np.asarray(cat) <op> other'.","messagePattern":"Cannot compare a Categorical for op (.+?) with type (.+?)\\.\nIf you want to compare values, use 'np\\.asarray\\(cat\\) <op> other'\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":188,"sourceCode":"\n                if opname not in {\"__eq__\", \"__ge__\", \"__gt__\"}:\n                    # GH#29820 performance trick; get_loc will always give i>=0,\n                    #  so in the cases (__ne__, __le__, __lt__) the setting\n                    #  here is a no-op, so can be skipped.\n                    mask = self._codes == -1\n                    ret[mask] = fill_value\n                return ret\n            else:\n                return ops.invalid_comparison(self, other, op)\n        else:\n            # allow categorical vs object dtype array comparisons for equality\n            # these are only positional comparisons\n            # (hashable list-likes such as tuple/range take the branch above and\n            #  are already treated as scalar-like, so only non-standard\n            #  positional list-likes like ``deque`` warn here, GH#62423)\n            ops.maybe_warn_listlike(other)\n            if opname not in [\"__eq__\", \"__ne__\"]:\n                raise TypeError(\n                    f\"Cannot compare a Categorical for op {opname} with \"\n                    f\"type {type(other)}.\\nIf you want to compare values, \"\n                    \"use 'np.asarray(cat) <op> other'.\"\n                )\n\n            if isinstance(other, ExtensionArray) and needs_i8_conversion(other.dtype):\n                # We would return NotImplemented here, but that messes up\n                #  ExtensionIndex's wrapped methods\n                return op(other, self)\n            return getattr(np.array(self), opname)(np.array(other))\n\n    func.__name__ = opname\n\n    return func\n\n\ndef contains(cat, key, container) -> bool:\n    \"\"\"","sourceCodeStart":170,"sourceCodeEnd":206,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L170-L206","documentation":"Raised when a non-equality comparison (__lt__/__gt__/__le__/__ge__) is attempted between a Categorical and a non-Categorical, non-hashable list-like operand. Pandas only supports positional ordering comparisons against scalars or other Categoricals; arbitrary list-likes are ambiguous so it directs you to explicitly convert via np.asarray.","triggerScenarios":"`cat < [1,2,3]` or `cat >= some_series` where the right side is a list-like and the op is not == or !=. The hashable branch (scalar/tuple category) is exempt; only list-likes hit this.","commonSituations":"Comparing a categorical column against a parallel list/Series expecting element-wise ordering; or feeding a list of thresholds to a categorical mask.","solutions":["Convert to numpy first as the message suggests: `np.asarray(cat) < other`.","If you meant comparing each element to one threshold, pass a scalar: `cat < threshold`.","Reconsider whether the categorical should be ordered and compared against a scalar category instead."],"exampleFix":"# before\ncat = pd.Categorical(['a','b','c'], ordered=True)\ncat < ['c','a','b']\n# after\nimport numpy as np\ncat = pd.Categorical(['a','b','c'], ordered=True)\nnp.asarray(cat) < ['c','a','b']","handlingStrategy":"fallback","validationCode":"import numpy as np\n\ndef cat_ordering_compare(cat, other, op):\n    import operator\n    if not np.isscalar(other):\n        return op(np.asarray(cat), np.asarray(other))\n    return op(cat, other)","typeGuard":"def is_scalar_or_hashable(x) -> bool:\n    import numpy as np\n    from pandas.api.types import is_hashable\n    return np.isscalar(x) or is_hashable(x)","tryCatchPattern":"try:\n    res = cat < other_listlike\nexcept TypeError as e:\n    if 'Cannot compare a Categorical' in str(e):\n        import numpy as np\n        res = np.asarray(cat) < np.asarray(other_listlike)\n    else:\n        raise","preventionTips":["For list-wise ordering comparisons, convert with np.asarray first.","Reserve categorical ordering comparisons for scalars or other categoricals.","Document which comparisons are element-wise vs scalar in your pipeline."],"tags":["categorical","comparison","list-like","typeerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}