pandas-dev/pandas · error · TypeError

Cannot multiply StringArray by bools. Explicitly cast to int

Error message

Cannot multiply StringArray by bools. Explicitly cast to integers instead.

What it means

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.

Source

Thrown at pandas/core/arrays/string_.py:1264

                    stacklevel=find_stack_level(),
                )
            if len(other) != len(self):
                # prevent improper broadcasting when other is 2D
                raise ValueError(
                    f"Lengths of operands do not match: {len(self)} != {len(other)}"
                )

            # for array-likes, first filter out NAs before converting to numpy
            if not is_array_like_deprecate_non_pandas(other):
                other = np.asarray(other)
            other = other[valid]

        other_dtype = getattr(other, "dtype", None)
        if op.__name__.strip("_") in ["mul", "rmul"] and (
            lib.is_bool(other) or lib.is_np_dtype(other_dtype, "b")
        ):
            # GH#62595
            raise TypeError(
                "Cannot multiply StringArray by bools. "
                "Explicitly cast to integers instead."
            )

        if op.__name__ in ops.ARITHMETIC_BINOPS:
            result = np.empty_like(self._ndarray, dtype="object")
            result[mask] = self.dtype.na_value
            result[valid] = op(self._ndarray[valid], other)
            if not lib.is_string_array(result, skipna=True):
                return result
            return self._from_backing_data(result)
        else:
            # logical
            result = np.zeros(len(self._ndarray), dtype="bool")
            result[valid] = op(self._ndarray[valid], other)
            res_arr = BooleanArray(result, mask)
            if self.dtype.na_value is np.nan:
                if op == operator.ne:

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Cast the bool operand to int before multiplying: `arr * mask.astype(int)` or `arr * mask.view('i1')`.
  2. If you actually meant to repeat/select strings, use boolean indexing `arr[mask]` instead of multiplication.
  3. If the bool came from a comparison, reconsider whether multiplication is the right operation at all.

Example fix

# before
s = pd.Series(['a','b'], dtype='string')
out = s * (s == 'a')
# after
out = s * (s == 'a').astype('int64')
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
import pandas as pd
from pandas._libs import lib

def safe_string_mul(arr, other):
    other_dt = getattr(other, 'dtype', None)
    if lib.is_bool(other) or (other_dt is not None and other_dt.kind == 'b'):
        raise TypeError('bool operand: cast to int first')
    return arr * other

Type guard

def is_bool_operand(other) -> bool:
    import numpy as np
    from pandas._libs import lib
    dt = getattr(other, 'dtype', None)
    return lib.is_bool(other) or (dt is not None and getattr(dt, 'kind', None) == 'b')

Try / catch

try:
    result = s * mask
except TypeError as e:
    if 'Cannot multiply StringArray by bools' in str(e):
        result = s * mask.astype('int64')
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/70ccad7aae54da03. Report an issue: GitHub.