{"record":{"id":"70ccad7aae54da03","repo":"pandas-dev/pandas","slug":"cannot-multiply-stringarray-by-bools-explicitly-c","errorCode":null,"errorMessage":"Cannot multiply StringArray by bools. Explicitly cast to integers instead.","messagePattern":"Cannot multiply StringArray by bools\\. Explicitly cast to integers instead\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":1264,"sourceCode":"                    stacklevel=find_stack_level(),\n                )\n            if len(other) != len(self):\n                # prevent improper broadcasting when other is 2D\n                raise ValueError(\n                    f\"Lengths of operands do not match: {len(self)} != {len(other)}\"\n                )\n\n            # for array-likes, first filter out NAs before converting to numpy\n            if not is_array_like_deprecate_non_pandas(other):\n                other = np.asarray(other)\n            other = other[valid]\n\n        other_dtype = getattr(other, \"dtype\", None)\n        if op.__name__.strip(\"_\") in [\"mul\", \"rmul\"] and (\n            lib.is_bool(other) or lib.is_np_dtype(other_dtype, \"b\")\n        ):\n            # GH#62595\n            raise TypeError(\n                \"Cannot multiply StringArray by bools. \"\n                \"Explicitly cast to integers instead.\"\n            )\n\n        if op.__name__ in ops.ARITHMETIC_BINOPS:\n            result = np.empty_like(self._ndarray, dtype=\"object\")\n            result[mask] = self.dtype.na_value\n            result[valid] = op(self._ndarray[valid], other)\n            if not lib.is_string_array(result, skipna=True):\n                return result\n            return self._from_backing_data(result)\n        else:\n            # logical\n            result = np.zeros(len(self._ndarray), dtype=\"bool\")\n            result[valid] = op(self._ndarray[valid], other)\n            res_arr = BooleanArray(result, mask)\n            if self.dtype.na_value is np.nan:\n                if op == operator.ne:","sourceCodeStart":1246,"sourceCodeEnd":1282,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/string_.py#L1246-L1282","documentation":"Raised by StringArray's arithmetic dispatcher when a multiplication (mul/rmul) operand is a Python bool or a numpy bool dtype. Since pandas GH#62595, multiplying an object-backed StringArray by booleans is treated as a programming error because the result is meaningless (True repeats once, False empties the string) and usually indicates the caller meant integers. The fix is to explicitly cast the bool operand to int so the intent is unambiguous.","triggerScenarios":"Calling `string_array * True`, `string_array * np.bool_(True)`, or multiplying a `StringDtype()` ('string[python]') Series by a boolean Series/scalar. The check at pandas/core/arrays/string_.py:1260 matches op names 'mul'/'rmul' against lib.is_bool or a 'b' numpy dtype and raises TypeError.","commonSituations":"Using a boolean mask column as a multiplier instead of as an index; piping DataFrame.filter()/comparison output directly into arithmetic; migrating code that relied on the old implicit bool-to-int coercion.","solutions":["Cast the bool operand to int before multiplying: `arr * mask.astype(int)` or `arr * mask.view('i1')`.","If you actually meant to repeat/select strings, use boolean indexing `arr[mask]` instead of multiplication.","If the bool came from a comparison, reconsider whether multiplication is the right operation at all."],"exampleFix":"# before\ns = pd.Series(['a','b'], dtype='string')\nout = s * (s == 'a')\n# after\nout = s * (s == 'a').astype('int64')","handlingStrategy":"validation","validationCode":"import numpy as np\nimport pandas as pd\nfrom pandas._libs import lib\n\ndef safe_string_mul(arr, other):\n    other_dt = getattr(other, 'dtype', None)\n    if lib.is_bool(other) or (other_dt is not None and other_dt.kind == 'b'):\n        raise TypeError('bool operand: cast to int first')\n    return arr * other","typeGuard":"def is_bool_operand(other) -> bool:\n    import numpy as np\n    from pandas._libs import lib\n    dt = getattr(other, 'dtype', None)\n    return lib.is_bool(other) or (dt is not None and getattr(dt, 'kind', None) == 'b')","tryCatchPattern":"try:\n    result = s * mask\nexcept TypeError as e:\n    if 'Cannot multiply StringArray by bools' in str(e):\n        result = s * mask.astype('int64')\n    else:\n        raise","preventionTips":["Never feed boolean masks into * on string arrays; use .loc[mask] for selection.","Add a dtype-kind unit test asserting string arithmetic operands are int/float.","Lint for `* (` patterns near boolean comparisons in string-typed code."],"tags":["string-array","arithmetic","boolean","typeerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}