pandas-dev/pandas · error · TypeError

Invalid value for dtype 'str'. Value should be a string or m

Error message

Invalid value for dtype 'str'. Value should be a string or missing value (or array of those).

What it means

When _validate_setitem_value receives a non-scalar (array-like) value, it checks every element with lib.is_string_array(value, skipna=True). If any element is neither a str nor NA-like, it raises TypeError with the generic 'dtype str' message. This guards bulk assignment like arr[mask] = [...].

Source

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

                value = self.dtype.na_value
            elif not isinstance(value, str):
                raise TypeError(
                    f"Invalid value '{value}' for dtype '{self.dtype}'. Value should "
                    f"be a string or missing value, got '{type(value).__name__}' "
                    "instead."
                )
        else:
            value = extract_array(value, extract_numpy=True)
            if not is_array_like_deprecate_non_pandas(value):
                value = np.asarray(value, dtype=object)
            elif isinstance(value.dtype, type(self.dtype)):
                return value
            else:
                # cast categories and friends to arrays to see if values are
                # compatible, compatibility with arrow backed strings
                value = np.asarray(value)
            if len(value) and not lib.is_string_array(value, skipna=True):
                raise TypeError(
                    "Invalid value for dtype 'str'. Value should be a "
                    "string or missing value (or array of those)."
                )
        return value

    def __setitem__(self, key, value) -> None:
        if self._readonly:
            raise ValueError("Cannot modify read-only array")

        value = self._validate_setitem_value(value)

        key = check_array_indexer(self, key)
        scalar_key = lib.is_scalar(key)
        scalar_value = lib.is_scalar(value)
        if scalar_key and not scalar_value:
            raise ValueError("setting an array element with a sequence.")

        if not scalar_value:

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert every element to str before bulk assignment: [str(v) for v in values].
  2. Replace missing entries with pd.NA or np.nan rather than non-string sentinels.
  3. Use pd.array(values, dtype='string') to build a coerced array, then assign it.

Example fix

// before
string_array[[0, 1]] = [1, 2]

// after
string_array[[0, 1]] = [str(1), str(2)]
Defensive patterns

Strategy: validation

Validate before calling

clean = [str(v) if not (pd.isna(v) or isinstance(v, str)) else v for v in values]
string_array[key] = clean

Type guard

import pandas as pd

def all_strings_or_na_array(values) -> bool:
    return all(isinstance(v, str) or pd.isna(v) for v in values)

Prevention

When it happens

Trigger: Calling string_array[[0,1]] = [1, 2], string_array[:] = ['a', 3], or assigning a list/array containing non-string, non-NA elements to multiple positions.

Common situations: Bulk-updating a string column from a numeric intermediate; assigning the output of a mapping that returned mixed types.

Related errors


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